我需要调用一个作为参数传递给另一个函数的函数,并且必须首先传递它所需的参数.在c ++中,这个问题通过宏来解决:
#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");
}
Run Code Online (Sandbox Code Playgroud)
它可以输出:
> 72
> Called!
Run Code Online (Sandbox Code Playgroud)
这正是我需要在D中调用函数的方法.任何想法?
编辑:我需要在D中完成这个.我想在CALL中调用"foo",如:
CALL(foo(9, 8)) // and not like: CALL(foo, 9, 8)
Run Code Online (Sandbox Code Playgroud)
但是我不知道这在D中是如何实现的.也许是用mixin?
Ada*_*ppe 13
在D中,您可以使用lazy函数参数.
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));
}
Run Code Online (Sandbox Code Playgroud)
D的lazy参数存储类使编译器在一个小的匿名函数中包装你给它的任何东西.以上就好像你写的:
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); } );
}
Run Code Online (Sandbox Code Playgroud)
但编译器会为您重写它.这就是为什么我说lazy void- void你传递的隐藏函数的返回类型.如果它返回int,你可以lazy int改用.
请注意,由于函数x内部CALL被重写为隐藏函数,因此调用它两次实际上会对参数进行两次求值:
void CALL(lazy void x) {
writeln("before called");
x;
writeln("after called");
x;
writeln("after called again");
}
Run Code Online (Sandbox Code Playgroud)
会做:
before called
3 5
after called
3 5
after called again
Run Code Online (Sandbox Code Playgroud)
注意它是如何打印两次参数的.就像C宏一样.但如果这不是您想要的,只需将其分配给一个临时的:
void CALL(lazy int x) {
auto tmp = x;
// you can now use tmp as a plain int
}
Run Code Online (Sandbox Code Playgroud)