C++ std::function operator=

C++ std::function operator=

本文关键字:operator function C++ std      更新时间:2023-10-16

我无法在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吗?

你的问题在这里:

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

Integer::displayJson const&,不带显式参数绑定它。我的gcc拒绝这样的绑定表达式,但是cpp.sh的编译器和我的clang都允许这个编译,可能不正确,因为语言标准声明:

*INVOKE* (fd, w1, w2, ..., wN) [font =宋体][要求]是有效的某些值w1, w2,…的表达式, wN,其中N == sizeof...(bound_args)

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

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

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

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