Default arguments for template parameters (C++ only)

Template parameters may have default arguments. The set of default template arguments accumulates over all declarations of a given template. The following example demonstrates this:

template<class T, class U = int> class A;
template<class T = float, class U> class A;

template<class T, class U> class A {
   public:
      T x;
      U y;
};

A<> a;

The type of member a.x is float, and the type of a.y is int.

You cannot give default arguments to the same template parameters in different declarations in the same scope. For example, the compiler will not allow the following:

template<class T = char> class X;
template<class T = char> class X { };

If one template parameter has a default argument, then all template parameters following it must also have default arguments. For example, the compiler will not allow the following:

template<class T = char, class U, class V = int> class X { };

Template parameter U needs a default argument or the default for T must be removed.

The scope of a template parameter starts from the point of its declaration to the end of its template definition. This implies that you may use the name of a template parameter in other template parameter declarations and their default arguments. The following example demonstrates this:

template<class T = int> class A;
template<class T = float> class B;
template<class V, V obj> class C;
// a template parameter (T) used as the default argument
// to another template parameter (U)
template<class T, class U = T> class D { };

Related information