zoukankan      html  css  js  c++  java
  • 用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;
        }

     

  • 相关阅读:
    iOS 苹果开发证书失效的解决方案(Failed to locate or generate matching signing assets)
    iOS NSArray数组过滤
    App Store2016年最新审核规则
    iOS 根据字符串数目,自定义Label等控件的高度
    iOS 证书Bug The identity used to sign the executable is no longer valid 解决方案
    Entity FrameWork 增删查改的本质
    EF容器---代理类对象
    Entity FrameWork 延迟加载本质(二)
    Entity FrameWork 延迟加载的本质(一)
    Entity FrameWork 增删查改
  • 原文地址:https://www.cnblogs.com/TianFang/p/2891623.html
Copyright © 2011-2022 走看看