Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

c++ - std::function not compiling in VS2012

I am trying to compile the following code taken from here but I am getting a compile error. Does anyone have any ideas what might be wrong?

The code

#include <iostream>
#include <functional>

struct Foo {
    Foo(int num) : num_(num) {}
    void print_add(int i) const { std::cout << num_+i << '
'; }
    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);
}

The compile error :

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> *' 

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This looks like a bug in VS2012, I have made a bug report here.

For now the following works :

Edit: edited based on Xeo's suggestion to use std::mem_fn

#include <iostream>
#include <functional>

struct Foo {
    Foo(int num) : num_(num) {}
    void print_add(int i) const { std::cout << num_+i << '
'; }
    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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...