Is it possible to convert a delegate into a function?

Dicebot public at dicebot.lv
Thu Feb 6 14:14:59 PST 2014


On Thursday, 6 February 2014 at 21:26:06 UTC, Gary Willoughby 
wrote:
> I know you can convert functions into delegates using: 
> http://dlang.org/phobos/std_functional.html#.toDelegate but can 
> you do this the other way around?
>
> I have a method that needs a function pointer but it would be 
> nice to use a converted delegate pointer instead.

auto toFunction(DG)(DG dg)
{
	assert(!dg.ptr);
	return dg.funcptr;
}

void foo(int function() input)
{
	import std.stdio;
	writeln(input());
}

void main()
{
	int boo()
	{
		return 42;
	}
	
	// foo(&boo); // fails
	foo(toFunction(&boo)); // prints "42"
}


More information about the Digitalmars-d-learn mailing list