2016-11-18 8 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;

で来ています。 std::functionはコピーできませんか?

+0

コンパイラは恐らくエラーメッセージを発していましたか? – juanchopanza

+0

ラムダ/クロージャがあるのでバインドが役に立たないと思っている人もいるので、 'auto f = [this](Json j) - > Json {return display(j);};'を代わりに使用するといいです – PeterT

+1

'#include ' –

答えて

2

あなたの問題はここにある:

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

Integer::displayJson const&を取り、あなたは明示的な引数でそれをバインドします。私のgccが、このようなバインド式を拒否しますが、両方cpp.shのコンパイラと私の打ち鳴らすは、その言語の標準状態ので、おそらく間違って、このコンパイルをしましょう:[func.require]いくつかの有効な 表現しなければならない

*INVOKE* (fd, w1, w2, ..., wN)W1、W2、...、wNからあなたのバインドされた関数オブジェクトfが正しいことによって、あなたの問題を解決することができます N == sizeof...(bound_args)

、 - ちょうどJson引数のプレースホルダを追加します。

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

demo

2

Integer::display()は1つのパラメータをとります。これをプレースホルダとして指定する必要があります。そうでない場合は、std::bindから生成されたファンクタのシグネチャは何も取らないとみなされ、function<Json(Json)>のシグネチャと一致しません。

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

LIVE

関連する問題