I need to pass a bind function to another function but i am getting error that there is no conversion available-
cannot convert argument 2 from 'std::_Bind<true,std::string,std::string (__cdecl *const )(std::string,std::string),std::string &,std::_Ph<2> &>' to 'std::function<std::string (std::string)> &'
The function:
std::string keyFormatter(std::string sKeyFormat, std::string skey)
{
boost::replace_all(sKeyFormat, "$ID$", skey);
return sKeyFormat;
}
The usage is like -
auto fun = std::bind(&keyFormatter, sKeyFormat, std::placeholders::_2);
client(sTopic, fun);
The client function looks like-
void client(std::function<std::string(std::string)> keyConverter)
{
// do something.
}
std::bind is for partial function application. That is, suppose you have a function object f which takes 3 arguments: f(a,b,c); You want a new function object which only takes two arguments, defined as: g(a,b) := f(a, 4, b);
Internally, std::bind() detects that a pointer to a member function is passed and most likely turns it into a callable objects, e.g., by use std::mem_fn() with its first argument.
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.
You are using the wrong placeholders
, you need _1
:
auto fun = std::bind(&keyFormatter, sKeyFormat, std::placeholders::_1);
The number of the placeholder is not here to match the position of the args, but rather to choose which arguments to send to the original function in which position:
void f (int, int);
auto f1 = std::bind(&f, 1, std::placeholders::_1);
f1(2); // call f(1, 2);
auto f2 = std::bind(&f, std::placeholders::_2, std::placeholders::_1);
f2(3, 4); // call f(4, 3);
auto f3 = std::bind(&f, std::placeholders::_2, 4);
f3(2, 5); // call f(5, 4);
See std::bind
, especially the examples at the end.
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