c++ member function as callback

For the usage of bind wrapping member functions, simply make a note.

Bind all parameters, member functions as thread execution functions:

When addressing a member function, add a class name space, and then bind the this pointer.

#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 some parameters, member functions as callback functions

If you only bind a part of the parameters, you can also use bind to achieve it.
Here std::placeholders::_1 is used as a placeholder, and the this pointer is specified to be bound to the first parameter. Subsequent calls can then pass the second parameter.

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;
}

};

That's what handwritten code means.

Guess you like

Origin blog.csdn.net/yuanlulu/article/details/127420577