用boost.signal实现多播委托

使用boost.signal

boost.signal提供了一个多播委托机制,通过它可以非常容易的实现观察者模式:

    void print_sum(float x, float y)
    {
        std::cout << "The sum is " << x+y << std::endl;
    }

    void print_product(float x, float y)
    {
        std::cout << "The product is " << x*y << std::endl;
    }

    void print_difference(float x, float y)
    {
        std::cout << "The difference is " << x-y << std::endl;
    }

    int main()
    {
        boost::signal<void (float, float)> sig;

        sig.connect(print_sum);
        sig.connect(print_product);
        sig.connect(print_difference);

        sig(5, 3);
    }

signal对象的使用方式非常简单,connect连接回调,disonnect去连接回调,()运算符执行所有回调

连接成员函数

通过lambda表达式也可以非常容易的实现成员函数的连接:

    struct A
    {
        int value;
        A(int value) : value(value) {}
        void Foo() { cout << "a has value of " << value << endl; }
    };

    int main()
    {
        A a(123);
        boost::signal<void ()> sig;

        sig.connect([&]() {a.Foo();});
        sig();
    }

连接带返回值的函数

signal也支持带返回值的函数,和C#一样,只返回最后一个函数的返回值

    boost::signal<int ()> sig;
    sig.connect([](){ return 1; });
    sig.connect([](){ return 2; });
    sig.connect([](){ return 3; });
    cout << sig() << endl;

异常处理

signal的异常处理机制也和c#一样:遇到异常后停止执行,抛出异常

    sig.connect([](){ cout << "foo 1" << endl; });
    sig.connect([](){ throw std::exception("foo 2 fail"); });
    sig.connect([](){ cout << "foo 3" << endl; });

    try
    {
        sig();
    }
    catch (std::exception& error)
    {
        cout << error.what() << endl;
    }

 

原文地址:https://www.cnblogs.com/TianFang/p/2891623.html