函数模板的显式专用化

利用函数模板,您可以通过为特定类型提供函数模板的显式专用化(重写)来定义该类型的特殊行为。 例如:

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

此声明使您能够为 double 变量定义不同函数。 与非模板函数相似,也会应用标准类型转换(如将 float 类型的变量提升到 double)。

示例

// 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()
{
}

另请参阅

函数模板