Thread overview
fuction Return function
Jul 26, 2014
seany
Jul 26, 2014
sigod
Jul 26, 2014
Meta
July 26, 2014
Can a function return a function in D? Sorry if i missed the answer somewhere
July 26, 2014
On Saturday, 26 July 2014 at 20:49:30 UTC, seany wrote:
> Can a function return a function in D? Sorry if i missed the answer somewhere

Just alias your function signature:

```d
alias MyFunctionType = void function(int);
```

Example from my own code:
```d
alias DeserializeBody = TLObject function(InBuffer);

DeserializeBody[uint] registerAll(modules...)()
{
    // ...
}
```

July 26, 2014
On Saturday, 26 July 2014 at 20:49:30 UTC, seany wrote:
> Can a function return a function in D? Sorry if i missed the answer somewhere

Yup, you can return functions, delegates, or function pointers.

int function(int) returnsFunc1()
{
	return function(int n) { return n; };
}

int function(int) returnsFunc2()
{
        //Even works for nested functions.
        //Make them static so they don't
        //create a context pointer to
        //returnsFunc2's frame
	static int fun(int n)
	{
		return n;
	}
	
	return &fun;
}

int test(int n)
{
	return n;
}

int function(int) returnsFunc3()
{
	return &test;
}

int delegate(int) makeAdder(int numToAdd)
{
	return delegate(int n) { return n + numToAdd; };
}

void main()
{
	auto func1 = returnsFunc1();
	assert(func1(1) == 1);
	
	auto func2 = returnsFunc2();
	assert(func2(2) == 2);
	
	auto func3 = returnsFunc3();
	assert(func3(3) == 3);
	
	auto add3 = makeAdder(3);
	assert(add3(1) == 4);
}