Use boost. signal
Boost. signal provides a multicast delegation mechanism through which the observer mode can be easily implemented:
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 );
}
The usage of the signal object is very simple. The connect connection callback, The disonnect to connect the callback, and the () operator to execute all the callbacks.
Connect member functions
Lambda expressions can easily connect member functions:
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 ();
}
Connect functions with return values
Signal also supports functions with return values. Like C #, only the return values of the last function are returned.
Boost: signal <int ()> sig;
Sig. connect ([] () {return 1 ;});
Sig. connect ([] () {return 2 ;});
Sig. connect ([] () {return 3 ;});
Cout <sig () <endl;
Exception Handling
The exception handling mechanism of signal is the same as that of c #: When an exception occurs, it stops execution and throws an exception.
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;
}