如何用Lambda表达式替换boost::bind?成员函数场景实现咨询
替换boost::bind为Lambda表达式的实现方法
你的成员函数myFunction是类的const成员函数,原boost::bind代码的作用是绑定当前对象实例(this),并接收两个参数分别传入成员函数的input和output参数。对应的Lambda表达式写法如下:
[this](const std::vector<double>& input, std::vector<double>& output) -> bool { return this->myFunction(input, output); }
关键细节说明
- 捕获
this:因为要调用当前类的成员函数,lambda需要捕获当前对象的指针this,确保能访问成员函数myFunction。 - 参数匹配:lambda的参数列表完全对应
myFunction的参数类型,和原boost::bind中的_1、_2一一对应。 - 返回值简化:C++11及以上编译器能自动推导返回值类型,因此可以省略显式的返回值声明,简化为:
[this](const std::vector<double>& input, std::vector<double>& output) { return this->myFunction(input, output); }
只要你的代码环境支持C++11及以上标准,这个Lambda写法的功能完全等价于原boost::bind代码。
内容的提问来源于stack exchange,提问作者user1408865
相关产品推荐
相关产品推荐

