Implement multicast delegation using boost. signal

Source: Internet
Author: User
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;
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.