The following code implements a function template foo
that accepts an arbitrary number of arguments, and subsequently handles each one while maintaining a positional index of that argument:
template<int index, typename T>
void foo_impl(T value)
{
// Do something with index/value
}
template<int index, typename T, typename... Rest>
void foo_impl(T value, Rest... values)
{
// Do something with index/value
// Recursively handle remaining arguments
foo_impl<index + 1>(values...);
}
template<typename... T>
void foo(T... args)
{
foo_impl<1>(args...);
}
int main()
{
foo("test", 42);
}
This recursively instantiates function templates until it reaches the base template that takes a single argument. Every function template instantiation of foo_impl
omits the template type arguments. Although this compiles with Clang, GCC, and MSVC, I'm not sure this is legal.
Is it legal to omit the template arguments as illustrated in the code example? If so, what are the specific rules? And have those rules changed between C++ Standards?