10

C++11 introduced default template arguments for function templates. See also Default template arguments for function templates.

But reading the C++ standard I could not find that it is legal to define a function template which use default template arguments for the first template argument, but not the other template arguments.

This would be the opposite of how default arguments are handled where all subsequent parameters must have a default argument supplied; or be a function parameter pack.

The difference between default arguments and default template arguments seems strange at a first glance, but allows for constructs as:

template <typename TException = std::exception, typename TObjectBuilder>
auto SwallowExceptions(const TObjectBuilder& rObjectBuilder) -> decltype(rObjectBuilder())
{
   try
   {
      return rObjectBuilder();
   }
   catch (const TException&)
   {
      return decltype(rObjectBuilder())();
   }
}

Is this legal C++ code and where in the standard can this be found?

Community
  • 1
  • 1
dalle
  • 18,057
  • 5
  • 57
  • 81

1 Answers1

11

I can't see a direct quote which allows it, but it is certainly allowed by omission:

N3337 [temp.param]/11: If a template-parameter of a class template or alias template has a default template-argument, each subsequent template-parameter shall either have a default template-argument supplied or be a template parameter pack. If a template-parameter of a primary class template or alias template is a template parameter pack, it shall be the last template-parameter. A template parameter pack of a function template shall not be followed by another template parameter unless that template parameter can be deduced or has a default argument (14.8.2).

So this is disallowed for class templates and alias templates, but allowed for function templates as the parameters which follow those with defaults could be deduced from the function arguments.

TartanLlama
  • 63,752
  • 13
  • 157
  • 193