コールバックとしてのC++メンバー関数

バインド ラッピング メンバー関数の使用法については、簡単にメモしておきます。

すべてのパラメータ、メンバー関数をスレッド実行関数としてバインドします。

メンバー関数をアドレス指定する場合は、クラス名前空間を追加してから、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 ポインターが最初のパラメーターにバインドされるように指定されています。後続の呼び出しでは 2 番目のパラメータを渡すことができます。

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

};

それが手書きコードの意味です。

おすすめ

転載: blog.csdn.net/yuanlulu/article/details/127420577