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.
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.
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With