C++11 styled callbacks?

Use std::function and lambdas (or std::bind()) to store callables:

#include <functional>
#include <iostream>


class Test
{
public:
      void blah() { std::cout << "BLAH!" << std::endl; }
};

class Bim
{
public:
      void operator()(){ std::cout << "BIM!" << std::endl; }
};

void boum() { std::cout << "BOUM!" << std::endl; }


int main()
{
    // store the member function of an object:
    Test test;  
    std::function< void() > callback = std::bind( &Test::blah, test );
    callback();

    // store a callable object (by copy)
    callback = Bim{};
    callback();

    // store the address of a static function
    callback = &boum;
    callback();

    // store a copy of a lambda (that is a callable object)
    callback = [&]{ test.blah(); }; // often clearer -and not more expensive- than std::bind()
    callback();
}      

Result:

BLAH!

BIM!

BOUM!

BLAH!

Compiles and run: http://ideone.com/T6wVp

std::function can be used as any copyiable object, so feel free to store it somewhere as a callback, like in object’s member. It also means that you can freely put it in standard containers, like std::vector< std::function< void () > > .

Also note that equivalent boost::function and boost::bind have been available for years.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)