Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11: Variadic Template Function Parameter Pack Expansion Execution Order

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?

like image 680
Andrew Tomazos Avatar asked Aug 21 '12 03:08

Andrew Tomazos


People also ask

What is a Variadic template 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 the use of Variadic templates?

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.

What are variadic functions in C?

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.

What is parameter pack in C++?

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.


1 Answers

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.

like image 74
David Avatar answered Oct 10 '22 20:10

David