我正在尝试学习std::function
,这是我的代码:
#include <iostream>
#include <functional>
struct Foo {
void print_add(int i){
std::cout << i << '\n';
}
};
typedef std::function<void(int)> fp;
void test(fp my_func)
{
my_func(5);
}
int main(){
Foo foo;
test(foo.print_add);
return 0;
}
编译器错误:
error: cannot convert 'Foo::print_add' from type 'void (Foo::)(int)' to type 'fp {aka std::function<void(int)>}'
test(foo.print_add);
如何使这项工作有效,即如何将成员函数作为参数传递?
最佳答案
print_add
是foo
的非静态成员函数,这意味着必须在Foo
的实例上调用它;因此它有一个隐式的第一个参数this
指针。
使用可捕获foo
实例并在其上调用print_add
的lambda。
Foo foo;
test([&foo](int i){ foo.print_add(i); });
另一个选择是使用
std::bind
绑定(bind)foo
实例:test(std::bind(&Foo::print_add, &foo, std::placeholders::_1));
Live demo
关于c++ - 如何使用成员函数初始化 `std::function`?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23962019/