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

标签 c++ function dictionary boost

我正在尝试将一个字符串映射到一个函数。该函数应该得到一个 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/

相关文章:

java - Map<String, Integer> 中的问题计数

C++ 计数排序

jquery - 切换功能的更好方法

function - Common Lisp 函数没有返回值

javascript - 回调函数不执行

python - 如何使相等数字参数出现的键值

python - 根据子字典的值对字典中的子字典进行排序

c++ - WlanConnect 连接尝试失败

c++ - 定义宏时 "##x"是什么意思

c++ - VS 总是寻找预编译头文件