user1095108
user1095108

Reputation: 14603

::std::initializer_list vs variadic templates

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

Upvotes: 6

Views: 4416

Answers (3)

Nicol Bolas
Nicol Bolas

Reputation: 473447

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.

Upvotes: 4

akim
akim

Reputation: 8759

On occasions I had used variadic template functions just like yours, but then realized that I needed more parameters, possibly templated. In that case typename... A is too eager, and I was happy to rely on braces on the call site to clearly specify where the variadic list of arguments ends, and where the following optional arguments started.

Upvotes: 1

Smeeheey
Smeeheey

Reputation: 10316

You can iterate over an std::initializer_list in a way that you cannot over a parameter pack (unless you have C++17 and you fold it first). So for example you can have for loops with the lists. With parameter packs, you only option to expand them is via recursive specialised definitions.

Upvotes: 3

Related Questions