如何将std :: bind对象传递给函数

use*_*270 7 c++ c++11

我需要将绑定函数传递给另一个函数,但是我收到的错误是没有可用的转换 -

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)> &'
Run Code Online (Sandbox Code Playgroud)

功能:

std::string keyFormatter(std::string sKeyFormat, std::string skey)
{
    boost::replace_all(sKeyFormat, "$ID$", skey);
    return sKeyFormat;
}
Run Code Online (Sandbox Code Playgroud)

用法如下 -

auto fun = std::bind(&keyFormatter, sKeyFormat, std::placeholders::_2);
client(sTopic, fun);
Run Code Online (Sandbox Code Playgroud)

客户端功能看起来像 -

void client(std::function<std::string(std::string)> keyConverter)
{
    // do something.
}
Run Code Online (Sandbox Code Playgroud)

Hol*_*olt 8

您使用的是错误的placeholders,您需要_1:

auto fun = std::bind(&keyFormatter, sKeyFormat, std::placeholders::_1);
Run Code Online (Sandbox Code Playgroud)

占位符的数量不是为了匹配args的位置,而是选择将哪些参数发送到原始函数的哪个位置:

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);
Run Code Online (Sandbox Code Playgroud)

请参阅std::bind,特别是最后的示例.