Search code examples
c++templatesparameter-pack

Is there any regular pattern to figure out where to put ... in templates?


I got confused with the location where the ... should be put when using template parameter packs.

For example, in template parameter list, we should use typename ...Ts, while in a parameter list, it becomes Ts...ts.

When instantiate a template, it becomes tuple<Ts...> and most confused me is std::forward<Args>(args)..., the ... is out side the parentheses. Until then, I force myself to just remember this, until today I see this: sizeof...(Params), I think I must understand the regular pattern to avoid further confused.

So could anybody help how to treat the ... to fully understand the location where to put it?


Solution

  • It follows the thing being repeated. A name that follows is like multiple names.

    In template<typename... Ts> we are declaring multiple typenames, e.g. template<typename Ts0, typename Ts1, typename Ts2>.

    In void foo(Ts... ts), we are declaring multiple parameters, using the multiple types, e.g. void foo(Ts0 ts0, Ts1 ts1, Ts2 ts2)

    In std::tuple<Ts...> we are using the multiple types to instantiate std::tuple, e.g. std::tuple<Ts0, Ts1, Ts2>

    In std::forward<Args>(args)... we are using multiple expressions, e.g. std::forward<Args0>(args0), std::forward<Args1>(args1), std::forward<Args2>(args2)

    sizeof... is a named operator, distinct from sizeof