An introduction to Boost Signals

By , last updated May 14, 2016
ldv

Signals with lambdas

Lambdas are really easy to use with signals.

#include <stdio.h>              // std::cout
#include <boost/signals2.hpp>   // boost::signals2

int main()
{
    // Shortcut typedefs
    typedef boost::signals2::signal<void(double)>   registration_manager;
    typedef registration_manager::slot_type         registration_request;

    // Define the signal handler
    registration_manager signalHandler;

    // Make a named lambda
    auto namedLambda = [&]( double value )
    {
        std::cout << "Lambda input value: " << value << std::endl;
    };

    // Connect the class to this handle,
    // for this we're using boost::bind
    signalHandler.connect( namedLambda );       // Named lambda defined above

    // Connect to inline lambda
    signalHandler.connect( [&]( double value )
    {
        std::cout << "Inline lambda input value: " << value << std::endl;
    }); // Defined here

    // Call the handlers
    signalHandler( 3.14 );

    // Output should be:
    // Lambda input value: 3.14
    // Inline lambda input value: 3.14

    return 0;
}

Professional Software Developer, doing mostly C++. Connect with Kent on Twitter.

Comments

  1. Tama May 14, 2016 Leave a Reply

    It’s unreadable because of &gt &amp characters instead of the actual characters.

    • kent May 14, 2016 Leave a Reply

      Hi, thanks for letting us know.

      I’ve fixed it, and lets hope it stays like this. WordPress is stupid when it comes to code in posts. The editor will silently mangle and destroy code, when it’s trying to be “smart”.

      Kent

  2. ultrix March 13, 2017 Leave a Reply

    Hi,
    I cannot get over
    // Get message id
    const MessageId ID = MSG::MsgId;

    Compiler argues about this.
    Br,

    • Kent Fagerjord March 17, 2017 Leave a Reply

      Hi,

      The error can be anything, but I’d guess you’re not passing an actual message type as the parameter to that method.

      Or it could be an older compiler.

Leave a Reply


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*