【问题标题】:C++ std::function operator=C++ std::函数运算符=
【发布时间】:2016-11-18 06:34:38
【问题描述】:

我无法在 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不能被复制吗?

【问题讨论】:

  • 编译器是否可能发出错误消息?
  • 有些人认为 bind 现在没有用了,因为有 lambdas/closures,所以考虑 auto f = [this](Json j)-&gt;Json{return display(j);}; 作为替代
  • 你需要#include &lt;string&gt;
  • 我不知道为什么但它在这里编译http://cpp.sh/7w6c
  • @Mayank 可能包含在其他 stl 头文件中,例如 iostream。但不能保证。

标签: c++ c++11 stdmap std-function stdbind


【解决方案1】:

你的问题在这里:

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

Integer::display 接受 Json const&amp; 并且您绑定它时没有显式参数。我的 gcc 拒绝了这样的绑定表达式,但是 cpp.sh 的编译器和我的 clang 都允许它编译,可能是错误的,因为语言标准规定:

*INVOKE* (fd, w1, w2, ..., wN) [func.require] 应该是一个有效的 一些值的表达式 w1, w2, ..., wN,其中 N == sizeof...(bound_args)

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

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

demo

【讨论】:

    【解决方案2】:

    Integer::display() 接受一个参数。应指定为占位符,否则std::bind生成的functor的签名将被视为不带任何内容,与function&lt;Json(Json)&gt;的签名不匹配。

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

    LIVE

    【讨论】:

      猜你喜欢
      • 2013-01-29
      • 2016-02-05
      • 2011-09-30
      • 1970-01-01
      • 2021-01-14
      • 2012-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多