【问题标题】:VS2013 std::function with member function [duplicate]带有成员函数的VS2013 std::function [重复]
【发布时间】:2014-05-21 17:28:20
【问题描述】:

我正在尝试将 std::function 与这样的成员函数一起使用:

struct Foo
{
   void bar(int) const { /* ... */ }
};

//later on
std::function<void(const Foo&, int)> fun = &Foo::bar;

这在 GCC 4.8.1 下有效,但在 VS2013 下编译失败,出现以下错误:

error C2664: 'void std::_Func_class<_Ret,const Foo &,int>::_Set(std::_Func_base<_Ret,const Foo &,int> *)' :
cannot convert argument 1 from '_Myimpl *' to 'std::_Func_base<_Ret,const Foo &,int> *'

在我看来,它就像 VS 中的一个错误,但也许我什么也没看到?有没有办法解决它(没有像 boost 这样的外部库)?

编辑:我在条形签名中忘记了“const”。但这在 VS 中仍然不起作用。

【问题讨论】:

    标签: c++ visual-studio-2013 std-function member-functions


    【解决方案1】:

    std::function 需要接受指向成员函数的指针(INVOKE 的定义)。

    最简单的解决方法是改用std::mem_fn,或者用std::mem_fn包装构造函数参数:

    std::function<void(const Foo&, int)> fun = std::mem_fn(&Foo::bar);
    

    【讨论】:

      猜你喜欢
      • 2023-03-31
      • 1970-01-01
      • 2015-03-04
      • 1970-01-01
      • 2012-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-24
      相关资源
      最近更新 更多