c++11:std::bind

The thing is like this,
there are two classes, the member function in class A should be used as the callback function of class B.
Looking up the data, it is found that non-static member functions of classes before c++11 cannot be used as callback functions, and the compiler will report an error. This is because the member function of the class has a hidden this pointer, and the parameters of the function pointer of the callback function are determined in advance, so as long as most of them use ordinary functions or static functions as the callback pointer before.

After c++11 std::bind can solve this problem. E.g:


class A
{
    
    
public:
	bool make_callback(int a, std::string& s);//类的非静态成员函数
}


//声明函数指针类型,返回值类型bool, 参数类型int和std::string的引用
using callback = std::function<bool(int, std::string&)>;
class B
{
    
    
public:
	void setfunc(callback cb)
}

int main()
{
    
    
	using std::placeholders::_1;//占位符
	using std::placeholders::_2;
	B b;
	A a;
	// 记住,类的成员非静态函数就用&,传入的第一个参数必须是this,_1,_2表示回调函数的显示的参数
	b.setfunc(std::bind(&A::make_callback,&a,_1,_2))
}

Reference:
https://blog.csdn.net/sinat_27953939/article/details/97107766 is
more detailed than mine.

Guess you like

Origin blog.csdn.net/ynshi57/article/details/111412224