【问题标题】:Boost function map to string将函数映射到字符串
【发布时间】:2017-10-15 06:07:57
【问题描述】:

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

【问题讨论】:

  • 我会提醒您不要使用非标准标识符,例如 $A

标签: c++ function dictionary boost


【解决方案1】:

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

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

所以要解决它:

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

或者更简单的

f["$A"] = $A;

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

【讨论】:

    猜你喜欢
    • 2012-01-23
    • 2012-07-24
    • 2021-11-15
    • 2018-07-09
    • 2012-08-21
    • 1970-01-01
    • 2011-02-14
    • 2022-08-16
    • 2017-01-31
    相关资源
    最近更新 更多