VS2013 std :: function具有成员函数 [英] VS2013 std::function with member function

查看:243
本文介绍了VS2013 std :: function具有成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用std :: function的成员函数,像这样:

I'm trying to use std::function with member functions like this:

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

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

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

This works under GCC 4.8.1 but fails to compile under VS2013 with the following error:

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)?

It looks to me like a bug in VS but maybe I'm not seeing something? Is there a way to workaround it (without external libs like boost)?

编辑:我忘了const但这在VS中仍然无效。

I forgot "const" in bar signature. But this still doesn't work in VS.

推荐答案

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

std::function is required to accept pointers to member functions (definition of INVOKE).

最简单的解决方法是改用 std :: mem_fn ,或者使用 std :: mem_fn

The simplest workaround is to use std::mem_fn instead, or wrap the constructor argument with std::mem_fn:

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

这篇关于VS2013 std :: function具有成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆