对于bind包装成员函数的用法,简单做个笔记。
绑定全部参数,成员函数作为线程执行函数:
对成员函数取址时要加类名空间,再bind绑定好this指针。
#include <memory>
#include <thread>
class MyClass {
public:
int starthread(){
m_thread_ptr = std::make_shared<std::thread>(&MyClass::thread_loop_f, this);
m_thread_ptr->detach();
//do something
return 0;
}
private:
std::shared_ptr<std::thread> m_thread_ptr;
void thread_loop_f()
{
while(1) {
//do something
}
}
}
绑定一部分参数,成员函数作为回调函数
如果只绑定一部分参数,也可以用bind来实现。
这里使用std::placeholders::_1作为占位符,指定this指针和第一个参数绑定。后续调用再传第二个参数即可。
using result_cb = std::function<void (int num)>;
int use_cb(result_cb &cb) {
int result = 1;
cb(result);
return 0;
}
class MyClass{
public:
void process_result(int num) {
printf("num:%d\n", num);
}
int start()
{
//这里将第一个参数和this指针绑定,其他地方就能直接调用成员函数了
result_cb cb = std::bind(&MyClass::process_result, this, std::placeholders::_1);
use_cb(cb);
return 0;
}
};
手写代码,意思就是这么个意思。