C++ std::function 运算符=
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)
[func.require] shall be a valid
expression for some values w1, w2, ..., wN, where
N == sizeof...(bound_args)
您可以通过使绑定函数对象 f
正确来解决您的问题 - 只需为 Json
参数添加一个占位符:
auto f = bind(&Integer::display, this, placeholders::_1);
我无法用 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)
[func.require] shall be a valid expression for some values w1, w2, ..., wN, whereN == sizeof...(bound_args)
您可以通过使绑定函数对象 f
正确来解决您的问题 - 只需为 Json
参数添加一个占位符:
auto f = bind(&Integer::display, this, placeholders::_1);