2017-10-15 156 views
1

我试图将一个字符串映射到函数。该功能应该得到一个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; 
} 
+0

我会提醒你不要使用非标准的标识符,比如'$ A'。 – StoryTeller

回答

1

在你的榜样错误,使用boost::bind完全是多余的。你可以直接指定函数本身(它将被转换为一个指向函数的指针,并且被boost::function删除)。

既然你确实绑定了,仅仅传递函数是不够的。绑定时需要给出boost::bind参数,或者指定占位符如果您希望绑定对象将某些内容转发给您的函数。你可以在错误信息中看到它,这就是boost::_bi::list0

因此,要解决这个问题:

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

或者简单的

f["$A"] = $A; 

而且,正如我在注释中提到你,我建议你避开那些不规范的标识符。 A $在根据C++标准的标识符中不是有效的标记。一些实现可能支持它,但并非所有的都需要。