如何让接收std::function的模板函数支持任意参数?能否不用std::bind?
问题2:不使用std::bind传入成员函数
完全可以,常用方法有两种:
方法1:Lambda表达式(最推荐)
通过lambda捕获对象,直接调用成员函数,语法简洁且类型安全:
int main() { Cls ccc; // 无参成员函数 test3([&ccc]() { return ccc.foo(); }); // 带参成员函数示例:假设Cls有int bar(int a) // test3([&ccc](int a) { return ccc.bar(a); }, 5); }
方法2:std::mem_fn
std::mem_fn将成员函数转换为可调用对象,需传入实例作为参数:
#include <functional> int main() { Cls ccc; // 需配合思路2中的任意可调用版本test3 test3(std::mem_fn(&Cls::foo), ccc); }
内容的提问来源于stack exchange,提问作者DuduArbel
相关产品推荐
相关产品推荐

