gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 18:26:15 24 4
gpt4 key购买 nike

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

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.
}

最佳答案

您使用了错误的占位符,您需要_1:

auto fun = std::bind(&keyFormatter, sKeyFormat, std::placeholders::_1);

这里占位符的数量不是为了匹配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);

参见 std::bind ,尤其是最后的例子。

关于c++ - 如何将 std::bind 对象传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37607584/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com