C++ 如何将std::bind结果存储到std::function
我想存储对C++ 如何将std::bind结果存储到std::function,c++,stdbind,C++,Stdbind,我想存储对std::function>对象的回调。当我使用lambda时,效果很好。但是,当我对成员函数使用std::bind时,它会出现编译错误 这是示例错误代码 #include <functional> #include <iostream> using namespace std; class A { public: void foo() { std::function<int(int,int)> callback
std::function>
对象的回调。当我使用lambda时,效果很好。但是,当我对成员函数使用std::bind
时,它会出现编译错误
这是示例错误代码
#include <functional>
#include <iostream>
using namespace std;
class A
{
public:
void foo()
{
std::function<int(int,int)> callback = std::bind(&A::calc, this);
// std::function<int(int,int)> callback = [this](int a, int b) { return this->calc(a, b); }; // lambda works fine
int r = callback(3, 4);
cout << r << endl;
}
int calc(int b, int c) { return b + c; }
};
int main()
{
A a;
a.foo();
return 0;
}
#包括
#包括
使用名称空间std;
甲级
{
公众:
void foo()
{
std::function callback=std::bind(&A::calc,this);
//std::function callback=[this](inta,intb){返回this->calc(a,b);};//lambda工作正常
int r=回调(3,4);
cout您需要指出A::calc
接受2个参数,使用std::placeholders::X
执行此操作:
std::function<int(int,int)> callback = std::bind(&A::calc, this, std::placeholders::_1,std::placeholders::_2);
std::function callback=std::bind(&A::calc,this,std::placeholders::_1,std::placeholders::_2);
std::function
用于存储可调用对象,以便其他人可以设置变量。因此,auto不是一个可接受的选项。顺便说一句,std::bind
与lambda相比没有什么优势,只是使用起来更复杂。在一些罕见的情况下,lambda没有帮助,但您需要绑定,尽管我从未遇到过红色一您可以直接执行此操作,而无需使用绑定:std::函数回调(&A::calc,this);
。由于回调的签名是已知的,因此可以推断占位符吗
std::function<int(int,int)> callback = std::bind(&A::calc, this, std::placeholders::_1,std::placeholders::_2);