2016-11-18 132 views
0

我无法编译C++ 11中的简单程序。 你可以在这里看看http://cpp.sh/9muxfC++ std :: function operator =

#include <functional> 
#include <iostream> 
#include <exception> 
#include <tuple> 
#include <map> 

using namespace std; 

typedef int Json; 
typedef string String; 

class Integer/*: public PluginHelper*/ 
{ 
public: 
    Json display(const Json& in) 
    { 
     cout << "bad" << endl; 
     return Json(); 
    } 

    map<String, function<Json(Json)>>* getSymbolMap() 
    { 
     static map<String, function<Json(Json)>> x; 
     auto f = bind(&Integer::display, this); 
     x["display"] = f; 
     return nullptr; 
    } 
}; 

问题在行x["display"] = f;

你有很大的帮助,如果你让我明白发生了什么在这里:)到来。 Can std::function不能被复制?

+0

没有编译器或许发出错误讯息? – juanchopanza

+0

有些人认为绑定现在没用了,因为有lambda/closures,所以考虑'auto f = [this](Json j) - > Json {return display(j);};'作为替代 – PeterT

+1

您需要'#include ' –

回答

2

你的问题就在这里:

auto f = bind(&Integer::display, this); 

Integer::display需要Json const&你绑定它没有明确的参数。我的GCC拒绝这样的绑定表达式,但两者cpp.sh的编译器和我的铿锵让这个编译,可能是不正确的,因为语言标准规定:

*INVOKE* (fd, w1, w2, ..., wN) [func.require]应是一些有效的 表达值W1,W2,...,WN,其中 N == sizeof...(bound_args)

您可以通过您的绑定函数对象f正确解决您的问题 - 只需添加一个占位符Json参数:

auto f = bind(&Integer::display, this, placeholders::_1); 

demo

2

Integer::display()取一个参数。您应该指定它作为占位符,否则从std::bind生成的仿函数的签名将被视为无效,这与function<Json(Json)>的签名不匹配。

auto f = bind(&Integer::display, this, std::placeholders::_1); 
//          ~~~~~~~~~~~~~~~~~~~~~ 
x["display"] = f; 

LIVE

相关问题