I have some lambda functions which I want to bind using either boost::bind or std::bind. (Don't care which one, as long as it works.) Unfortunately both of them give me different compiler erros:
auto f = [](){ cout<<"f()"<<endl; };
auto f2 = [](int x){ cout<<"f2() x="<<x<<endl; };
std::bind(f)(); //ok
std::bind(f2, 13)(); //error C2903: 'result' : symbol is neither a class template nor a function template
boost::bind(f)(); //error C2039: 'result_type' : is not a member of '`anonymous-namespace'::<lambda0>'
boost::bind(f2, 13)(); //error C2039: 'result_type' : is not a member of '`anonymous-namespace'::<lambda1>'
So, what is the simplest workaround for this?
boost::bind is a generalization of the standard functions std::bind1st and std::bind2nd. It supports arbitrary function objects, functions, function pointers, and member function pointers, and is able to bind any argument to a specific value or route input arguments into arbitrary positions.
_1 is a placeholder. Boost. Bind defines placeholders from _1 to _9 . These placeholders tell boost::bind() to return a function object that expects as many parameters as the placeholder with the greatest number.
std::bind is a Standard Function Objects that acts as a Functional Adaptor i.e. it takes a function as input and returns a new function Object as an output with with one or more of the arguments of passed function bound or rearranged.
std::bind. Returns a function object based on fn , but with its arguments bound to args . Each argument may either be bound to a value or be a placeholder: - If bound to a value, calling the returned function object will always use that value as argument.
You need to manually specify the return type:
boost::bind<void>(f)();
boost::bind<int>(f2, 13)();
You can also write yourself a template-function to deduce the return type automagically using Boost.FunctionTypes to inspect your lambda's operator(), if you don't like to explicitly tell bind.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With