std :: function在VS2012中没有编译

Bar*_*klı 10 c++ visual-c++ c++11 visual-studio-2012

我正在尝试编译从这里获取的以下代码,但我收到编译错误.有没有人有任何想法可能是错的?

代码

#include <iostream>
#include <functional>

struct Foo {
    Foo(int num) : num_(num) {}
    void print_add(int i) const { std::cout << num_+i << '\n'; }
    int num_;
};


int main()
{
    // store a call to a member function
    std::function<void(const Foo&, int)> f_add_display = &Foo::print_add;
    Foo foo(314159);
    f_add_display(foo, 1);
}
Run Code Online (Sandbox Code Playgroud)

编译错误:

Error   1   error C2664: 'std::_Func_class<_Ret,_V0_t,_V1_t>::_Set' : 
cannot convert parameter 1 from '_Myimpl *' to 'std::_Func_base<_Rx,_V0_t,_V1_t> *' 
Run Code Online (Sandbox Code Playgroud)

谢谢.

Bar*_*klı 7

这看起来像VS2012中的一个错误,我在这里做了一个bug报告.

目前以下工作:

编辑:根据Xeo的建议编辑使用std :: mem_fn

#include <iostream>
#include <functional>

struct Foo {
    Foo(int num) : num_(num) {}
    void print_add(int i) const { std::cout << num_+i << '\n'; }
    int num_;
};

int main()
{
    // store a call to a member function
    std::function<void(const Foo&, int)> f_add_display = std::mem_fn(&Foo::print_add);
    Foo foo(314159);
    f_add_display(foo, 1);
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,对于那些使用2013年的人,我实际上能够重现相同的错误,即使它已经提交给2012年.我希望其他人也能证实这一点. (7认同)
  • 你的代码有点奇怪.你绑定`foo`并且仍然有一个`std :: function <void(const Foo&,int)>`.这有效的唯一原因是因为`std :: bind`吞下不需要的参数.你在问题中尝试的正确的等价物是使用`std :: mem_fn(&Foo :: print_add)`. (2认同)