【问题标题】:Compare std::function created with std::bind比较使用 std::bind 创建的 std::function
【发布时间】:2017-11-28 15:05:55
【问题描述】:

这是一个玩具示例

#include <iostream>
#include <functional>

struct Obj
{
  int x;

  int foo()
  {
    return 42;
  }
};

int main()
{
  Obj a, b;
  std::function<int()> f1 = std::bind(&Obj::foo, &a);
  std::function<int()> f2 = std::bind(&Obj::foo, &b);
  std::function<int()> f3 = std::bind(&Obj::foo, &a);
  std::function<int()> f4 = std::bind(&Obj::foo, &b);
}

如何验证f1 == f3f2 == f4,这里的== 比较器表示两个std::function 对象对应同一个对象的相同方法?

【问题讨论】:

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


    【解决方案1】:

    你没有。

    如果您想要==,您必须编写自己的类型擦除包装器,可能使用std::function 来存储状态。

    由于std::bind 不支持== 而lamba 也不支持,您必须注入一个确实 支持== 的自定义函数对象才能被类型擦除。

    这些都不容易。替代解决方案,例如使用名称注册绑定,将更加实用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-16
      • 2011-08-16
      • 2016-12-18
      • 2013-04-16
      • 2019-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多