Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

::std::initializer_list vs variadic templates

Tags:

c++

c++17

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 ...

like image 951
user1095108 Avatar asked May 10 '16 13:05

user1095108


People also ask

What is Variadic template in C++?

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.

What is std :: Initializer_list?

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 .


1 Answers

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.

like image 51
Nicol Bolas Avatar answered Nov 05 '22 15:11

Nicol Bolas