[英]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.