Explicit Specialization of Function Templates

HomeOverviewHow Do I

With a function template, you can define special behavior for a specific type by providing a explicit specialization (override) of the function template for that type. For example:

void MySwap( double a, double b);

This declaration enables you to define a different function for double variables. Like other nontemplated functions, standard type conversions (such as promoting a variable of type float to double) are applied.

Visual C++ 5.0, and later, now supports the new syntax for declaring explicit specializations of function templates. For example:

template<class T> void f(T t) {...};

//Explicit specialization of f with 'char' with the
//template argument explicitly specified:
//
template<> void f<char>(char c){...}

//Explicit specialization of f with 'double' with the
//template argument deduced:
//
template<> void f(double d) {...}

The following form of old syntax is also supported:

//Explicit specialization of f with 'char' with the
//template argument deduced:
//
void f(char) {...}

See Also   Function Template Instantiation