Reputation: 631
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.
}
Upvotes: 11
Views: 10427
Reputation: 37606
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.
Upvotes: 11
Reputation: 712
Your client function looks like it's incomplete. You probably want the following:
void client(const std::string &, std::function<std::string(std::string)> keyConverter);
Also, the placeholder should be std::placeholders::_1
.
A complete example would be:
#include <iostream>
#include <functional>
#include <string>
std::string keyFormatter(std::string sKeyFormat, std::string skey) {
return sKeyFormat;
}
void client(std::string, std::function<std::string(std::string)> keyConverter) {
// do something.
}
int main() {
auto sKeyFormat = std::string("test");
auto sTopic = std::string("test");
auto fun = std::bind(&keyFormatter, sKeyFormat, std::placeholders::_1);
client(sTopic, fun);
}
Upvotes: 4