Explicit Specialization of Function Templates

 

The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com.

The latest version of this topic can be found at Explicit Specialization of Function Templates.

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

template<> void MySwap(double a, double b);  

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

// explicit_specialization.cpp  
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)  
{  
}  
int main()  
{  
}  

Function Templates

Show: