Function parameter pack specialization

57 Views Asked by At
template <typename T, typename ... Ts>
void foo(T , Ts ... )
{
}

template <typename ... Ts, typename T>
void bar(T , Ts ... )
{
}

int main()
{
  foo<int, char>(1, 'c'); // well formed
  foo(1, 'c');

  // bar<int, char>(1, 'c'); // ill formed
  bar(1, 'c');
}

Why does explicitly specializing the template parameter function not work in the second case (bar)? It's obvious that the reason is that the parameter pack comes first in the argument-list, but still... why?

In the end of the day both cases work fine with implicit deduction. Explicitly specifying the arguments should only make it easier for the compiler.

To the person who flagged it for duplicate, I am not talking about "normal parameters" if anything like that even exists. Also I am not asking whether I can place a parameter pack before a paremeter, I am asking why I cannot explicitly specify the template arguments when pack comes first in the argument-list.

1

There are 1 best solutions below

0
Brian Bi On

A parameter pack is "greedy", so when you put Ts first and then explicitly specify template arguments as int, char, the pack gobbles up all the arguments specified, i.e., Ts is int, char and T has not been specified yet. T is deduced from the type of the first argument, but that means the resulting declaration of bar has parameter-type-list int, int, char, since int was deduced for T but int, char was explicitly specified for Ts. So this particular specialization of bar requires 3 arguments but you've only provided 2.