C++自定义Delegate作为函数参数传入的实现疑问
C++自定义Delegate作为函数参数传入的实现疑问
兄弟,我来帮你把这个问题捋清楚~
首先你要明确:你自己定义的Delegate类就是一个普通的C类,所以当你想把它作为参数传给函数时,直接用Delegate(或者更高效的const Delegate&)作为参数类型就行,完全不需要用auto(当然C17及以后auto作为函数参数也能运行,但直接写明确的类型会更清晰)。
然后你代码里有个关键误区要注意:d(42)是执行这个Delegate的调用(也就是触发了A::foo(42)),它的返回值是void,根本不能作为参数传给printString。你要传的是Delegate对象本身,然后在printString函数内部再去调用它。
修正后的代码示例
首先修改printString函数:
#include <iostream> #include <string> // 要确保Delegate类的定义在这个函数之前 void printString(const std::string& str, const Delegate& d) { std::cout << str << std::endl; // 在这里调用Delegate,传入你需要的参数 d(42); // 如果你想灵活控制参数,也可以把参数作为额外参数传入: // void printString(const std::string& str, const Delegate& d, int x) { d(x); } }
然后修改main函数的调用部分:
int main() { A a; Delegate d = Delegate::from_function<A, &A::foo>(&a); d(42); // 直接调用Delegate printString("foo", d); // 传Delegate对象本身,而不是调用后的结果 }
额外小提示
如果你以后想让这个Delegate支持不同的函数签名(比如返回值不是void,或者参数个数/类型不同),可以用模板来扩展这个Delegate类,但就你当前的需求来说,上面的写法完全能解决问题。
备注:内容来源于stack exchange,提问作者fewaf
相关产品推荐
相关产品推荐

