将函数映射到字符串

时间:2017-10-15 06:07:57

标签: c++ function dictionary boost

我正在尝试将字符串映射到函数。该函数应该传入*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;
}

我的代码在

下面
{{1}}

1 个答案:

答案 0 :(得分:2)

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

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

所以要解决它:

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

或者更简单

f["$A"] = $A;

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