boost.signal提供了一个多播委托机制,通过它可以非常容易的实现观察者模式:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
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表达式也可以非常容易的实现成员函数的连接:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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#一样,只返回最后一个函数的返回值。
1
2
3
4
5
|
boost:: signal < int ()> sig; sig.connect([](){ return 1; }); sig.connect([](){ return 2; }); sig.connect([](){ return 3; }); cout << sig() << endl; |
异常处理
signal的异常处理机制也和c#一样:遇到异常后停止执行,抛出异常。
1
2
3
4
5
6
7
8
9
10
11
12
|
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; } |
到此这篇关于C++用boost.signal实现多播委托的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://www.cnblogs.com/TianFang/archive/2013/02/04/2891623.html