Consider the following code:
template<class T>
size_t f(T t, size_t& x) { return x++; }
template<class... Args>
void g(Args... args)
{
size_t x = 0;
size_t y[] = { f(args, x)... };
for (size_t i = 0; i < sizeof...(args); i++)
assert(y[i] == i);
}
Is the assert guaranteed by the C++11 standard not to fire? Why or why not?
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.
With the variadic templates feature, you can define class or function templates that have any number (including zero) of parameters. To achieve this goal, this feature introduces a kind of parameter called parameter pack to represent a list of zero or more parameters for templates.
Variadic functions are functions that can take a variable number of arguments. In C programming, a variadic function adds flexibility to the program. It takes one fixed argument and then any number of arguments can be passed.
Parameter packs (C++11) A parameter pack can be a type of parameter for templates. Unlike previous parameters, which can only bind to a single argument, a parameter pack can pack multiple parameters into a single parameter by placing an ellipsis to the left of the parameter name.
Yes it's guaranteed not to fire. See the following quotes:
§14.5.3 Variadic templates:
Pack expansions can occur in [...] an initializer-list; the pattern is an initializer-clause.
§8.5.1 Aggregates:
The full-expressions in an initializer-clause are evaluated in the order in which they appear.
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