Imitate std::function to implement listener mode

template< class >
class function; /* undefined */

template< class R, class... Args >
class function<R(Args...)>

#include <functional>
#include <vector>
#include <iostream>

template<typename Signature>
struct Listener;

template<typename RET, typename... ArgTypes>
struct Listener<RET(ArgTypes...)>
{
    typedef std::function<void(ArgTypes...)> Functor;

    void reg(Functor&& functor)
    {
        functors.push_back(std::forward<Functor>(functor));
    }

    void notifyAll(ArgTypes... args)
    {
        for (const auto& f : functors)
        {
            f(args...);
        }
    }

private: 
    std::vector<Functor> functors;
};

void funcA(int i, double d)
{
    std::cout << i << " " << d << " " << __func__ << std::endl;
}

void funcB(const std::string& str)
{
    std::cout << str << " " << __func__ << std::endl;
}

int main(int argc, char* argv[])
{
    Listener<void(int, double)> obs;
    obs.reg(funcA);
    obs.notifyAll(1, 1);
    obs.notifyAll(1, 3.14);

    std::cout << "=======================================" << std::endl;

    Listener<int(const std::string&)> obs2;
    obs2.reg(funcB);
    obs2.notifyAll("hello");

    return 0;
}

Program stdout:

1 1 funcA
1 3.14 funcA
=======================================
hello funcB

 

Guess you like

Origin blog.csdn.net/xunye_dream/article/details/114681585