以下极简代码用于说明我的问题。这些代码不编译。如何使用 lambda 表达式或 std::bind
将函数成员作为参数传递?非常感谢您的帮助
#include <iostream>
using namespace std;
class ABC{
private:
int x =3;
int add2num(int a, int b){
return a+b+x;
}
int worker(int &fun(int a, int b), int a, int b){
return fun(a,b);
}
public:
int doSomething(int a, int b){
return worker(add2num, a, b);
}
};
int main() {
ABC test;
cout << test.doSomething(3,5) << endl;
return 0;
}
最佳答案
使用 lambda 和模板:
#include <iostream>
#include <functional>
using namespace std;
class ABC{
private:
int x =3;
int add2num(int a, int b){
return a+b+x;
}
template<class functor_t>
int worker(const functor_t& fun, int a, int b){
return fun(a,b);
}
public:
int doSomething(int a, int b) {
return worker([this](int a, int b){ return add2num(a, b); }, a, b);
}
};
int main() {
ABC test;
cout << test.doSomething(3,5) << endl;
return 0;
}
或者,不使用 lambda 但使用 std::bind
:
int doSomething(int a, int b) {
namespace ph = std::placeholders;
return worker(std::bind(&ABC::add2num, this, ph::_1, ph::_2), a, b);
}
其余代码无需修改,因为 worker
仍然是一个模板,因此可以接受任何可调用类型。
关于c++ - 如何将类中的函数作为参数传递给 C++11 中同一类中的另一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41360000/