我在尝试学习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
指针。
使用 lambda 捕获foo
实例和调用print_add
on it.
Foo foo;
test([&foo](int i){ foo.print_add(i); });
另一种选择是使用std::bind
来绑定foo
实例:
test(std::bind(&Foo::print_add, &foo, std::placeholders::_1));
现场演示 http://coliru.stacked-crooked.com/a/22acb8a78118f357
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)