Search code examples
c++functorboost-bindlvalue

boost::bind as l-value object


Is there way to do something like this (MS VS 2008)?

boost::bind mybinder = boost::bind(/*something is binded here*/);
mybinder(/*parameters here*/); // <--- first call
mybinder(/*another parameters here*/); // <--- one more call

I tried

int foo(int){return 0;}

boost::bind<int(*)(int)> a = boost::bind(f, _1);

but it doesn't work.


Solution

  • The bind returns unspecified type, so you can't directly create a variable of the type. There is however a type template boost::function that is constructible for any function or functor type. So:

    boost::function<int(int)> a = boost::bind(f, _1);
    

    should do the trick. Plus if you are not binding any values, only placeholders, you can do without the bind altogether, because function is constructible from function pointers too. So:

    boost::function<int(int)> a = &f;
    

    should work as long as f is int f(int). The type made it to C++11 as std::function to be used with C++11 closures (and bind, which was also accepted):

    std::function<int(int)> a = [](int i)->int { return f(i, 42); }
    

    note, that for directly calling it in C++11, the new use of auto is easier:

    auto a = [](int i)->int { return f(i, 42); }
    

    but if you want to pass it around, std::function still comes in handy.