觀察者2

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <string>
#include <functional>
#include <map>
#include <algorithm>
using namespace std;
class NonCopyable
ios

{
protected:
    NonCopyable() = default;
    ~NonCopyable()=default;
    NonCopyable(const NonCopyable& ) =delete;
    NonCopyable& operator=(const NonCopyable&)=delete;
函數

};
template<typename Func>
class Events : NonCopyable
spa

{server

private:
    int m_observerId =0;// 觀察者對應的編號
    std::map<int, Func>  m_connections; //觀察者列表
    //保存觀察者並分配觀察者的編號
    template<typename F>
    int Assign2(F&& f) {
        int k = m_observerId++;
        m_connections.emplace(k, std::forward<F>(f));
        return k;
    }
public:
    Events(){};
    ~Events(){}
    // 註冊觀察者 支持右值引用
    int Connect(Func&& f) {  return Assign2(f); }
    // 註冊觀察者
    int Connect(const Func& f) {  return Assign2(f); }
    void Disconnect(int key) { m_connections.erase(key); }
    // 通知全部的觀察者
    template<typename ... Args>
    void Notify(Args&&... args) {
        for(auto& it  : m_connections)
            it.second(std::forward<Args>(args)...);
    }
};
struct stAstring

{
    int a, b;
    void print(int a, int b){ cout<<a<<", "<<b<<endl; }
    void print2(){ cout<<a<<", "<<b<<endl; }
};
void print(int a, int b){ cout<<a<<", "<<b<<endl;}
void test1()
it

{
    Events<std::function<void(int, int)>> myevent;
    auto key = myevent.Connect(print);//以函數方式註冊觀察者
    stA  t;
    auto lambdakey = myevent.Connect([&t](int a, int b){ t.a=a; t.b=b; t.print2(); });
    //auto lambdakey = myevent.Connect([&t](int a, int b){ t.a=a; t.b=b;});
    std::function<void(int,int)> f = std::bind(&stA::print,&t, std::placeholders::_1,std::placeholders::_2);
    myevent.Connect(f);

    int a=11, b=12;
    myevent.Notify(a,b);
    cout<<"key = "<<key<<endl;
    myevent.Disconnect(key);
}
int main()
{
    test1();
    return 0;
}io

相關文章
相關標籤/搜索