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

how to pass a std::bind object to a function

本文关键字:函数 对象 bind std      更新时间:2023-10-16

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

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)> &'

该函数:

std::string keyFormatter(std::string sKeyFormat, std::string skey)
{
    boost::replace_all(sKeyFormat, "$ID$", skey);
    return sKeyFormat;
}

用法是这样的——

auto fun = std::bind(&keyFormatter, sKeyFormat, std::placeholders::_2);
client(sTopic, fun);

客户端函数如下所示-

void client(std::function<std::string(std::string)> keyConverter)
{
    // do something.
}

你用错了placeholders,你需要_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);

请参阅std::bind,尤其是最后的示例。

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

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

此外,占位符应std::placeholders::_1

一个完整的示例是:

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