#include <iostream> #include <sstream> #include <map> #include <signal.h> #include <stdio.h> #include <memory> #include <vector> #include <set> #include <assert.h> #include <unordered_map> #include <boost/thread.hpp> #include <boost/bind/bind.hpp> #include <queue> #include <Winsock2.h> #include <boost/progress.hpp> #include <boost/date_time/gregorian/gregorian.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/ref.hpp> #include <functional> #include <numeric> using namespace boost; using namespace std; class CObservable : boost::noncopyable { public: typedef boost::function<void(int)> Func; CObservable() : m_observerId(0) {} virtual ~CObservable(){} int Attach(const Func& f) { int k = m_observerId++; m_observers[k] = f; return k; } void Detach(int key) { m_observers.erase(key); } void Notify( int i ) { for ( auto it = m_observers.begin(); it != m_observers.end(); it++ ) { it->second(i); } } private: int m_observerId; std::map<int, Func> m_observers; }; struct stA { void print(int a) { cout << "stA=" << a << endl; } }; void print(int a) { cout << "print=" << a << endl; } int main(int argc, char **argv) { CObservable myObservable; myObservable.Attach(print); stA t; boost::function<void(int)> f = boost::bind(&stA::print, &t, _1); int key = myObservable.Attach(f); int a = 100; myObservable.Notify(a); myObservable.Detach(key); a = 999; myObservable.Notify(a); getchar(); return 0; }
时间: 2024-10-02 18:32:24