/
//BaseClass.h
#ifndef _BASECLASS_H_
#define _BASECLASS_H_#include "boost/function.hpp"
#include "boost/bind.hpp"
#include<iostream>
#include<string>
#include<list>
using namespace std;
typedef struct Func
{
boost::function<bool(int)> f;
string name;
};
class CButton
{
public:
bool ActionButtion(string signal, int i)
{
list<Func>::iterator it = m_signals.begin();
for(; it != m_signals.end(); ++it)
{
if((*it).name == signal)
{
(*it).f(i);
}
}
return true;
}
bool AddSignal(const Func &f)
{
m_signals.push_back(f);
return true;
}
private:
list<Func> m_signals;
};
class CPlayer
{
public:
bool play(int i){ cout << "play" << i << endl; }
bool playFast(int i){ cout << "playFast" << i << endl; }
bool stop(int i){ cout << "stop" << i << endl; }
};
class CPlayerBack
{
public:
bool freshBack(int i)
{
cout << "freshBack: " << i << endl;
}
};
#endif
/
//BaseClass.cpp
#include"BaseClass.h"
int main()
{
//生成一个按钮对象
CButton OnPlay;
//这是两个界面,当按钮有按下“click”等消息时,这两个界面可能同时改变
CPlayer play;
CPlayerBack playback;
//注册的三个消息响应函数
Func f1 = { boost::bind(&CPlayer::play, play, _1),"click"};
Func f3 = { boost::bind(&CPlayer::playFast, play, _1),"double_click"};
Func f4 = { boost::bind(&CPlayerBack::freshBack, playback, _1),"click"};
//在按钮中添加3个响应消息
OnPlay.AddSignal(f1);
OnPlay.AddSignal(f3);
OnPlay.AddSignal(f4);
//按钮在响应click时候,会调用上面两个不同类型的消息响应
OnPlay.ActionButtion("click", 1);
//同一个按钮还可以注册不同的消息
OnPlay.ActionButtion("double_click", 1);
CButton OnStop;
Func f2 = { boost::bind(&CPlayer::stop, play, _1),"click"};
OnStop.AddSignal(f2);
OnStop.ActionButtion("click", 1);
return 0;
}
/
//Makefile
a.out:Make
Make:
make -i clean
make target
target:
g++ -o a.out BaseClass.h BaseClass.cpp
clean:
rm a.out