Expansion with variadic templates [duplicate]

Originally I just literally answered the question, but I wanted to expand this somewhat to provide a more thorough explanation of how what packs are expanded into what. This is how I think about things anyway.

Any pack immediately followed by an ellipses is just expanded in place. So A<Ts...> is equivalent to A<T1, T2, ..., TN> and hun(vs...) is similarly equivalent to hun(v1, v2, ..., vn). Where it gets complicated is when rather than a pack followed by ellipses you get something like ((expr)...). This will get expanded into (expr1, expr2, ..., exprN) where expri refers to the original expression with any pack replaced with the ith version of it. So if you had hun((vs+1)...), that becomes hun(v1+1, v2+1, ..., vn+1). Where it gets more fun is that expr can contain more than one pack (as long as they all have the same size!). This is how we implement the standard perfect forwarding model;

foo(std::forward<Args>(args)...)

Here expr contains two packs (Args and args are both packs) and the expansion “iterates” over both:

foo(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), ..., std::forward<ArgN>(argN));

That reasoning should make it possible to quickly walk through your cases for, say, what happens when you call foo(1, 2, '3').

The first one, gun(A<Ts...>::hun(vs)...); expands Ts “in place” and then there’s an expression to expand for the last ellipses, so this calls:

gun(A<int, int, char>::hun(1), 
    A<int, int, char>::hun(2), 
    A<int, int, char>::hun('3'));

The second one, gun(A<Ts...>::hun(vs...)); expands both packs in place:

gun(A<int, int, char>::hun(1, 2, '3'));

The third one, gun(A<Ts>::hun(vs)...), expands both packs at the same time:

gun(A<int>::hun(1), 
    A<int>::hun(2), 
    A<char>::hun('3'));

[update] For completeness, gun(A<Ts>::hun(vs...)...) would call:

gun(A<int>::hun(1, 2, '3'),
    A<int>::hun(1, 2, '3'),
    A<char>::hun(1, 2, '3'));

Finally, there’s one last case to consider where we go overboard on the ellipses:

gun(A<Ts...>::hun(vs...)...);

This will not compile. We expand both Ts and vs “in place”, but then we don’t have any packs left to expand for the final ellipses.

Leave a Comment