Search code examples
c++c++11boostboost-bindboost-function

Rewrite boost flavored code in C++11 manner (Boost.Bind, Boost.Function)


I have some legacy code I'd like to rewrite in C++11 style. There are some boost::function defined as following

// void One::first(int)
boost::function<void()> a1 = boost::bind(&One::first, this, this->a); 

// void Two::second()
boost::function<void()> a2 = boost::bind(&Two::second, this); 

// void Three::third(int, const std::string &)
boost::function<void()> a3 = boost::bind(&Three::third, this, 8, str); 

These variables are passed to function foo in different places:

foo(somearg,  a1);          
foo(anotherarg, a2);
foo(othearg, a3);

where foo is defined like following

void foo(const Obj &obj, boost::function<void()> caller) {
  ...
  caller();
  ...
}

What is the best way to rewrite this code in C++11 style?


Solution

  • To start with, simply replace boost with std, and include the C++ header <functional> instead of the Boost headers. The standard function and bind are based on, and for the most part compatible with, the Boost versions.

    You could make it more generic:

    template <typename Function>
    void foo(const Obj &obj, Function caller) {
        //...
        caller();
        //...
    }
    

    and avoid the overhead (and, as the comments point out, obscure semantic restrictions) of the function wrapper:

    auto a1 = std::bind(&One::first, this, this->a); 
    foo(somearg, a1);
    

    You might find the lambda syntax more readable than a call to bind:

    auto a1 = [this]{first(a);};