[英]C++ std::function operator=
我無法在C ++ 11中編譯一個簡單程序。 您可以在這里http://cpp.sh/9muxf進行查看。
#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
嗎?
Integer::display()
采用一個參數。 您應將其指定為占位符,否則從std :: bind生成的函子的簽名將被視為不帶任何內容,與function<Json(Json)>
的簽名不匹配。
auto f = bind(&Integer::display, this, std::placeholders::_1);
// ~~~~~~~~~~~~~~~~~~~~~
x["display"] = f;
您的問題出在這里:
auto f = bind(&Integer::display, this);
Integer::display
接受Json const&
並且不使用顯式參數將其綁定。 我的gcc拒絕了這樣的綁定表達式,但是cpp.sh的編譯器和clang都允許該編譯,可能是錯誤的,因為語言標准指出:
*INVOKE* (fd, w1, w2, ..., wN)
wN*INVOKE* (fd, w1, w2, ..., wN)
[func.require]對於某些值w1,w2,..., wN是有效的表達式,其中N == sizeof...(bound_args)
您可以通過使綁定函數對象f
合適來解決問題-只需為Json
參數添加一個占位符:
auto f = bind(&Integer::display, this, placeholders::_1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.