Does passing multiple arguments via ::std::initializer_list
offer any advantages over the variadic function template method?
In code:
template <typename T> void f(::std::initializer_list<T> const);
template <typename ...A> void f(A&& ...args);
Note that the types A...
can be restricted to a single type as well, through SFINAE or static_assert()
. The arguments can be iterated through ...
A variadic template is a class or function template that supports an arbitrary number of arguments. This mechanism is especially useful to C++ library developers: You can apply it to both class templates and function templates, and thereby provide a wide range of type-safe and non-trivial functionality and flexibility.
An object of type std::initializer_list<T> is a lightweight proxy object that provides access to an array of objects of type const T .
There are advantages to having an initializer_list<T>
instead of a variadic template, assuming that either one would solve the problem.
For example, function definitions can only have so many parameters, even variadic ones. Implementations are allowed to have a hard limit, and the standard only requires that limit to be at least 256. The same goes for parameters in a function call.
By contrast, the number of values in a braced-init-list has a minimum limit of 16K (and implementations will usually permit far more). So if it's reasonable for the user to be calling this function with a gigantic set of values, initializer_list
is the only one where you can expect a compiler to work.
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