c++ - Why does this function template call work? -


the following code compiles:

template<int...> struct indices {};  template<int j, int ...i> void foo(indices<i...>) {}  int main(int argc, char **argv) {   foo<2>(indices<3,4,5>()); //why work?   return 0; } 

in function call, seems me j parameter becomes 2 , ...i parameter becomes 3,4,5?

but why work? specified 2 @ foo<2> meaning specified j 2 , ...i nothing. why can still specify ...i through indices argument? template mechanism being used here?

update: current answer not explain why can have 1 argument not deduced (explicitly specified) others deduced. when work? hope i'm not relying on undefined behavior. standard allow i'm doing above?

it's allowed specify part of parameters function call(first ones) if it's possible deduce other in compile time. example:

template<typename ret, typename arg> ret cast(arg x){     return x; }  cast<double>(5); 

actually may compile code:

template<int...> struct indices {};  template<int j, int ...i> void foo(indices<i...>) {}  int main(int argc, char **argv) {   foo<2,3>(indices<3,4,5>()); //ok 2,3,4,5 starts 2,3   return 0; } 

but not one:

template<int...> struct indices {};  template<int j, int ...i> void foo(indices<i...>) {}  int main(int argc, char **argv) {   foo<2,1>(indices<3,4,5>()); //no way make x,3,4,5 start 2,1   return 0; } 

see §14.1.8 part 3 of c++11 standard(n3242 draft).

trailing template arguments can deduced (14.8.2) or obtained default template-arguments may omitted list of explicit template-arguments. trailing template parameter pack (14.5.3) not otherwise deduced deduced empty sequence of template arguments. if of template arguments can deduced, may omitted; in case, empty template argument list <> may omitted. in contexts deduction done , fails, or in contexts deduction not done, if template argument list specified , it, along default template arguments, identifies single function template specialization, template-id lvalue function template specialization.


Comments