Search code examples
c++c++11stdmapstd-functionstdbind

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?


Solution

  • 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