1. 程式人生 > >C++ Boost signal2訊號/插槽知識點

C++ Boost signal2訊號/插槽知識點

signals2基於Boost的另一個庫signals,實現了執行緒安全的觀察者模式。在signals2中,觀察者模式被稱為訊號/插槽(signals and slots),它是一種函式回撥機制,一個訊號關聯了多個插槽,當訊號發出時,所有關聯它的插槽都會被呼叫。

下面就通過小案列來實現signal的使用

#include <iostream>
#include <boost\signals2.hpp>
#include <boost\function.hpp>
#include <boost\bind.hpp>

using namespace std;


class Button{

private:
	typedef boost::signals2::signal<void(int,int)> signalDef;
	typedef boost::signals2::signal<void(int,int)>::slot_type slotType;

private:
	signalDef mysignal;
	boost::signals2::connection mConnection;


public:
	boost::signals2::connection connectFun(const slotType& type){
		mConnection = mysignal.connect(type);
		return mConnection;
	}

	void sendSignal(){
		mysignal(10,20);
	}

};

void fun1(int a, int b){
	cout << "add result :" << a + b << endl;
}

void fun2(int a, int b){
	cout << "sub result :" << a - b << endl;
}

void fun3(int a ,int b){
	cout << "multi result :" << a * b << endl;
}


void main(){

	Button button;
	boost::signals2::connection con1 = button.connectFun(fun1);
	boost::signals2::connection con2 = button.connectFun(fun2);
	boost::signals2::connection con3 = button.connectFun(fun3);
	//con3.disconnect();
	while(1){

		system("pause");
		button.sendSignal();
	
	}


     cin.get();
}


下面槽函式是類的成員函式的時候

#include <iostream>
#include <boost\signals2.hpp>
#include <boost\bind.hpp>
#include <boost\function.hpp>

using namespace std;
using namespace boost;

template <typename signature>
class Signal{

public:
	//typedef 訊號
	typedef boost::signals2::signal<signature> defSignal;
    typedef typename defSignal::slot_type defSlot;

public:
	//連線槽函式
	boost::signals2::connection connectFun(const defSlot& slot);

	//過載偽函式
	void operator()(typename defSignal::template arg<0>::type a0,typename defSignal::template arg<1>::type a1);

private:
	defSignal mSignal;


};

//接收訊號後響應的函式
class FunRecv1{

public:
	void action(int a, int b){
	  cout << "add result" << a + b << endl;
	}

};

//接收訊號後響應的函式
class FunRecv2{

public:
	void action(int a, int b){
	  cout << "multi result" << a * b << endl;
	}

};
 
//實現
template <typename signature>
boost::signals2::connection  Signal<signature>::connectFun(const defSlot& slot){
	return mSignal.connect(slot);
}

template <typename signature>
void Signal<signature>::operator()(typename defSignal::template arg<0>::type a0,typename defSignal::template arg<1>::type a1){
	mSignal(a0,a1);
}
void main(){
    
	Signal<void(int,int)> mysignal;
	FunRecv1 fun1;
	FunRecv2 fun2;

	//boost::function<void(int,int)> myfun = boost::bind(&FunRecv1::action,&fun1,_1,_2);
	//訊號連線槽函式
	boost::signals2::connection con1 = mysignal.connectFun(boost::bind(&FunRecv1::action,&fun1,100,200));
	boost::signals2::connection con2 = mysignal.connectFun(boost::bind(&FunRecv2::action,&fun2,11,22));
	mysignal(100,200);

	con2.disconnect();
	mysignal(100,200);

    cin.get();
}


到這就能明白signal訊號機制的重要性 觀察者與被觀察者的模式

參考部落格:http://www.tuicool.com/articles/ZvYNze