An introduction to Boost Signals

By , last updated May 14, 2016

Signals calling members in classes

Using boost::bind to call members in classes.

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

class UtilityClass
{
    public:
        explicit UtilityClass()
        {
        }

        virtual ~UtilityClass()
        {
        }

    public:

        void handleSignal( double value )
        {
            std::cout << "Within a class: " << value << std::endl;
        }

        void handleHalfValue( double value )
        {
            std::cout << "Half: " << value / 2.0 << std::endl;
        }

};

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 class instance. std::unique_ptr is not possible, because we have to
    // 'share' the pointer in the bind expression below.
    typedef std::shared_ptr<UtilityClass>       UtilityClass_ptr;
    UtilityClass_ptr utils( new UtilityClass() );

    // Connect the class to this handle,
    // for this we're using boost::bind
    signalHandler.connect( boost::bind( &UtilityClass::handleSignal, utils, _1) );      // Defined above
    signalHandler.connect( boost::bind( &UtilityClass::handleHalfValue, utils, _1) );   // Defined above

    // Call the handlers
    signalHandler( 3.14 );

    // Output should be:
    // Within a class: 3.14
    // Half: 1.57

    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>

*