How to call a function passed as an argument with parameters already specified in D?

I need to call a function passed as an argument to another function, and first I need to pass the necessary arguments to it. In C ++, this problem is solved using a macro:

#include <iostream> #define CALL(x) x; \ std::cout << "Called!" << std::endl; void foo(int a, int b) { std::cout << a * b << std::endl; } int main() { CALL(foo(9, 8)); // I want to pass 2 int parameters inside 'foo' function call system("PAUSE"); } 

It outputs:

 > 72 > Called! 

This is how I need to call the function in D. Any ideas?

Edit: I need this to be done in D. I want to call "foo" inside CALL, for example:

 CALL(foo(9, 8)) // and not like: CALL(foo, 9, 8) 

But I do not know how this is achieved in D. Perhaps with mixin?

+7
d
source share
1 answer

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; // you can now use tmp as a plain int } 
+12
source share

All Articles