简体   繁体   中英

C++ std::function operator=

I am unable to compile a simple program in C++11. You can have a look at it here 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;
    }
};

The issue is coming at line x["display"] = f;

You be of great help if you make me understand what is happening here :). Can std::function not be copied?

Integer::display() takes one parameter. You should specify it as the placeholder, otherwise the signature of functor generated from std::bind will be regarded as taking nothing, which doesn't match the signature of function<Json(Json)> .

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

LIVE

Your problem lies here:

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

Integer::display takes Json const& and you bind it with no explicit arguments. My gcc rejects such a bind expression, but both cpp.sh's compiler and my clang let this compile, possibly incorrectly because the language standard states that:

*INVOKE* (fd, w1, w2, ..., wN) [func.require] shall be a valid expression for some values w1, w2, ..., wN , where N == sizeof...(bound_args)

You can fix your problem by making your bound function object f proper - just add a placeholder for the Json argument:

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

demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM