#include <functional>
#include <iostream>
class Foo{
void print(std::function<void (void)> f){
f();
std::cout << "!";
}
void sayHello(){
std::cout << "Hello";
}
public:
void tell(){
print(sayHello);
}
};
int main(){
auto foo = Foo();
foo.tell(); // 'Foo::sayHello': function call missing argument list; use '&Foo::sayHello' to create a pointer to member
}
我收到错误 C3867: 'Foo::sayHello': function call missing argument list;使用 '&Foo::sayHello' 创建指向成员的指针
。如果我使用 &Foo::sayHello
那么我会得到一堆模板错误。
我做错了什么?
最佳答案
sayHello
是一个非静态成员函数,因此它有一个隐含的第一个参数,即 this
指针。让代码正常工作的最简单方法是使用捕获 this
指针的 lambda 表达式。
void tell(){
print([this]{sayHello();});
}
另一个选项是 std::bind
void tell(){
print(std::bind(&Foo::sayHello, this));
}
关于c++ - 如何使用一个方法作为另一个方法的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23911869/