You do not need list initialization here
As others mentioned, you cannot use std::initializer_list
with references. You can use std::initializer_list<std::reference_wrapper<...>>
, but it will prevent your from passing rvalues as arguments to the constructor, because std::reference_wrapper
can only bind to lvalues. In other words, the following will not compile:
YourContainerOfFunctions C{ [](){} };
This makes usage of std::initializer_list
in your case neither efficient nor convenient.
Use variadic templates instead!
I believe that is what you wanted to achieve:
class Foo {
std::vector<std::function<void()>> Functions;
public:
template <class... FuncTs>
Foo(FuncTs &&...Funcs) : Functions({std::forward<FuncTs>(Funcs)...}) {}
};
void foo(){};
int main() {
auto boo = []() {};
std::function<void()> moo = []() {};
Foo F{
foo, boo, // passed by reference, then copied
[]() {}, // moved, then copied
std::move(moo) // moved, then also moved
};
}
This requires at most one copy per argument, necessary because std::function
always make a copy of functor object which it is constructed from. An exception is construction of std::function
from std::function
of the same type