I am having a lot of trouble using std::bind
in various places of my code. Sometimes it works, sometimes it doesn\'t, so I assume I am doing something fundament
The placeholder position objects (e.g. when you use _2
) is not the position of the argument in the function you call, but a placeholder for the argument in the created callable object. Instead always start with _1
and increase.
So:
auto bar_auto=std::bind(foo,1,_1);
etc.
This means you can switch the arguments in the object created by std::bind
by simply doing like
auto bar_auto=std::bind(foo,_2,_1);
When you "call" the bar_auto
object, the first argument will be the second argument to foo
, and the second argument in the call will be the first argument to foo
.
The _2
placeholder means to use second argument of the returned functor. Therefore the type of
std::bind(foo,1,_2)
is not std::function<int(int)>
but
std::function<int(unspecified_type, int)>
To get std::function<int(int)>
, use
std::bind(foo, 1, _1)
// ^^