gpt4 book ai didi

c++ - boost 函数映射到字符串

转载 作者:行者123 更新时间:2023-11-30 03:28:13 25 4
gpt4 key购买 nike

我正在尝试将一个字符串映射到一个函数。该函数应该得到一个 const char* 传入。我想知道为什么我一直收到错误

*no match for call to ‘(boost::_bi::bind_t<boost::_bi::unspecified, void (*)(const char*), boost::_bi::list0>) (const char*)’*

我的代码如下

#include <map>
#include <string>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>



typedef boost::function<void(const char*)> fun_t;
typedef std::map<std::string, fun_t> funs_t;



void $A(const char *msg)
{
std::cout<<"hello $A";
}

int main(int argc, char **argv)
{
std::string p = "hello";
funs_t f;
f["$A"] = boost::bind($A);
f["$A"](p.c_str());
return 0;
}

最佳答案

在您的示例中,使用 boost::bind 是完全多余的。您可以只分配函数本身(它将转换为指向函数的指针,并被 boost::function 删除类型就好了)。

既然你做了绑定(bind),仅仅传递函数是不够的。您需要在绑定(bind)时给 boost::bind 参数,或者如果您想让绑定(bind)对象将某些内容转发给您的函数,则指定一个占位符。您可以在错误消息中看到它,这就是 boost::_bi::list0 的用途。

所以要解决它:

f["$A"] = boost::bind($A, _1);

或者更简单

f["$A"] = $A;

此外,正如我在评论中向您指出的那样,我建议您避免使用不标准的标识符。根据 C++ 标准,$ 不是标识符中的有效标记。一些实现可能支持它,但并非所有实现都需要。

关于c++ - boost 函数映射到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46752215/

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