In D, you can use the lazy function parameter for this.
import std.stdio; void CALL(lazy void x) { writeln("before called"); x; writeln("after called"); } void foo(int x, int y) { writeln(x, " ", y); } void main() { CALL(foo(3, 5)); }
Parameter Storage Class
D lazy forces the compiler to wrap everything you give it in a small anonymous function. The above says as if you wrote:
import std.stdio; void CALL(void delegate() x) { // note delegate here in long-form syntax writeln("before called"); x(); writeln("after called"); } void foo(int x, int y) { writeln(x, " ", y); } void main() { // and this delegate too CALL( delegate() { return foo(3, 5); } ); }
But the compiler rewrites it for you. That's why I said lazy void - void , there is a return type of the hidden function that you pass. If he returned int , you could use lazy int .
Note that since x inside the CALL function is rewritten as a hidden function, calling it twice will actually evaluate the arguments twice:
void CALL(lazy void x) { writeln("before called"); x; writeln("after called"); x; writeln("after called again"); }
:
before called 3 5 after called 3 5 after called again
Notice how it prints the arguments twice. Like the C macro, actually. But if this is not what you want, just assign it to yourself:
void CALL(lazy int x) { auto tmp = x;
Adam D. Ruppe
source share