Explicit specialization (C++ only)

When you instantiate a template with a given set of template arguments the compiler generates a new definition based on those template arguments. You can override this behavior of definition generation. You can instead specify the definition the compiler uses for a given set of template arguments. This is called explicit specialization. You can explicitly specialize any of the following:
  • Function or class template
  • Member function of a class template
  • Static data member of a class template
  • Member class of a class template
  • Member function template of a class template
  • Member class template of a class template

Explicit specialization declaration syntax

Read syntax diagramSkip visual syntax diagramtemplate< >declaration_name <template_argument_list> declaration_body

The template<> prefix indicates that the following template declaration takes no template parameters. The declaration_name is the name of a previously declared template. Note that you can forward-declare an explicit specialization so the declaration_body is optional, at least until the specialization is referenced.

The following example demonstrates explicit specialization:
using namespace std;

template<class T = float, int i = 5> class A
{
   public:
      A();
      int value;
};

template<> class A<> { public: A(); };
template<> class A<double, 10> { public: A(); };

template<class T, int i> A<T, i>::A() : value(i) {
   cout << "Primary template, "
        << "non-type argument is " << value << endl;
}

A<>::A() {
   cout << "Explicit specialization "
        << "default arguments" << endl;
}

A<double, 10>::A() {
   cout << "Explicit specialization "
        << "<double, 10>" << endl;
}

int main() {
   A<int,6> x;
   A<> y;
   A<double, 10> z;
}
The following is the output of the above example:
Primary template non-type argument is: 6
Explicit specialization default arguments
Explicit specialization <double, 10>

This example declared two explicit specializations for the primary template (the template which is being specialized) class A. Object x uses the constructor of the primary template. Object y uses the explicit specialization A<>::A(). Object z uses the explicit specialization A<double, 10>::A().

C++0x Beginning of C++0x only.

Explicit specialization and inline namespace definitions

Inline namespace definitions are namespace definitions with an initial inline keyword. Members of an inline namespace can be explicitly instantiated or specialized as if they were also members of the enclosing namespace. For more information, see Inline namespace definitions (C++0x)

C++0x End of C++0x only.