Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 << '\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);
}

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.

like image 690
Barış Uşaklı Avatar asked Oct 27 '12 00:10

Barış Uşaklı


People also ask

Can std :: function be copied?

You can recover the desired behavior by always using thread-local copies of the std::function because they'll each have an isolated copy of the state variables.

What does std :: bind do in C++?

std::bind is a Standard Function Objects that acts as a Functional Adaptor i.e. it takes a function as input and returns a new function Object as an output with with one or more of the arguments of passed function bound or rearranged.

What is the point of std :: function?

Class template std::function is a general-purpose polymorphic function wrapper. Instances of std::function can store, copy, and invoke any Callable target -- functions, lambda expressions, bind expressions, or other function objects, as well as pointers to member functions and pointers to data members.

Why is std :: function slow?

If it is small, like 3-5 CPU instructions then yes std::function will make it slower, because std::function is not inlined into outer calling code. You should use only lambda and pass lambda as template parameter to other functions, lambdas are inlined into calling code.


1 Answers

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 << '\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);
}
like image 180
Barış Uşaklı Avatar answered Sep 22 '22 13:09

Barış Uşaklı