Understanding Default Template Arguments

Explore the rules that apply to the default template arguments.

In the previous lesson, we saw the use of a default template argument for a template parameter. This topic is explored in detail in this lesson.

Default template argument rules

Default template arguments are specified similarly to default function arguments, in the parameter list after the equal sign. The following rules apply to default template arguments:

  • They can be used with any kind of template parameters with the exception of parameter packs.

  • If a default value is specified for a template parameter of a class template, variable template, or type alias, then all subsequent template parameters must also have a default value. The exception is the last parameter if it’s a template parameter pack.

  • If a default value is specified for a template parameter in a function template, then subsequent template parameters are not restricted to also have a default value.

  • In a function template, a parameter pack may be followed by more type parameters only if they have default arguments or their value can be deduced by the compiler from the function arguments.

  • They are not allowed in declarations of friend class templates.

  • They are allowed in the declaration of a friend function template only if the declaration is also a definition and there’s no other declaration of the function in the same translation unit.

  • They are not allowed in the declaration or definition of an explicit specialization of a function template or member function template.

Examples of default template arguments

The following snippet shows examples of using default template arguments:

Get hands-on with 1200+ tech skills courses.