Consider the following code, in which std::function
is used three times to capture the methods of one class:
struct some_expensive_to_copy_class
{
void foo1(int) const { std::cout<<"foo1"<<std::endl; }
void foo2(int) const { std::cout<<"foo2"<<std::endl; }
void foo3(int) const { std::cout<<"foo3"<<std::endl; }
};
struct my_class
{
template<typename C>
auto getFunctions(C const& c)
{
f1 = [c](int i) { return c.foo1(i);};
f2 = [c](int i) { return c.foo2(i);};
f3 = [c](int i) { return c.foo3(i);};
}
std::function<void(int)> f1;
std::function<void(int)> f2;
std::function<void(int)> f3;
};
This, however, will perform three copies of the class some_expensive_to_copy_class
, which is inefficient as one could have guessed by the name.
Is there a workaround such that only one copy is made?
To emphasize it, I'm interested here in the approach using std::function
, not void
-pointers and also not the corresponding inheritance-based implementation.