函数模板的重载
更新:2007 年 11 月
在 Visual Studio .NET 中,编译器会将其签名映射到模板函数显式专用化的函数(即使该函数前面没有 template<>)视作专用化。现在,此类函数被视为非模板重载。
在诸如以下情况中,运行时行为可能会发生更改:
// bc_overloading_of_function_templates.cpp
#include <stdio.h>
template<class T>
void f(T) // called in Visual Studio .NET 2003
{
printf_s("in void f(T)\n");
}
void f(int) // called in Visual Studio .NET
// for identical behavior for both compiler versions, use
// template<> void
// f<int>(int)
{
printf_s("in void f(int)\n");
}
int main()
{
f<int>(3);
// Visual C++ .NET calls template function specialization
// because explicit template arguments were provided.
// The current compiler will also call specialization because
// explicit template arguments were provided.
// But these will call different functions because the previous
// compiler explicitly specializes on int, and the current
// compiler does not (creates non-template overload)
f(4);
// Visual C++ .NET will call template function specialization
// because no global non-template overload defined.
// The current compiler will call the non-template overload.
}
对于前面的示例,请注意,通过使 f(int) 成为显式专用化(而不是应重载的专用化),将可以实现相同的行为。在 Visual C++ 的 Visual Studio .NET 2003 和 Visual Studio .NET 版本中都将调用专用化。