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

C++ 如何将std::bind对象传递给函数,c++,c++11,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)>

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

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)> &'
用法是-

auto fun = std::bind(&keyFormatter, sKeyFormat, std::placeholders::_2);
client(sTopic, fun);
客户端函数看起来像-

void client(std::function<std::string(std::string)> keyConverter)
{
    // do something.
}
void客户端(std::function keyConverter)
{
//做点什么。
}

您使用了错误的
占位符,您需要
\u 1

auto fun = std::bind(&keyFormatter, sKeyFormat, std::placeholders::_1);
此处占位符的编号不是为了匹配参数的位置,而是为了选择要在哪个位置发送到原始函数的参数:

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);

请参阅,特别是最后的示例。

您的客户端功能看起来不完整。您可能需要以下内容:

void client(const std::string &, std::function<std::string(std::string)> keyConverter);

你确定这些是你函数的真实原型吗?如果
sKeyFormat
不是引用,则您的
keyFormatter
看起来可疑,plus
client
只接受一个参数。使用lambda而不是
std::bind
client接受一个参数,但这是一个函数指针获取一个字符串并返回一个字符串,这就是为什么我要用sKeyFormat绑定keyFormatter函数的第一个参数。我以前使用过lambda,但我不能使用lambda,因为我需要部署我拥有的linux和gcc版本上的代码不支持lambdas,尽管它支持std::bind和std::function
void client(const std::string &, std::function<std::string(std::string)> keyConverter);
#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);
}