我知道下面的代码是一个类的部分特化:
template <typename T1, typename T2>
class MyClass {
…
};
// partial specialization: both template parameters have same type
template <typename T>
class MyClass<T,T> {
…
};
我也知道 C++ 不允许函数模板部分特化(只允许完整)。但是我的代码是否意味着我已经为一个/相同类型的参数部分专门化了我的函数模板?因为它适用于 Microsoft Visual Studio 2010 Express!如果不是,那么您能否解释一下部分特化的概念?
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
template <typename T1, typename T2>
inline T1 max (T1 const& a, T2 const& b)
{
return a < b ? b : a;
}
template <typename T>
inline T const& max (T const& a, T const& b)
{
return 10;
}
int main ()
{
cout << max(4,4.2) << endl;
cout << max(5,5) << endl;
int z;
cin>>z;
}
最佳答案
按照标准,不允许函数部分特化。在示例中,您实际上是 重载而不是专门化 max<T1,T2>
功能。
如果允许的话,它的语法应该看起来有点如下:
// Partial specialization is not allowed by the spec, though!
template <typename T>
inline T const& max<T,T> (T const& a, T const& b)
{ // ^^^^^ <--- supposed specializing here as an example
return a; // can be anything of type T
}
对于函数模板,C++ 标准只允许完全特化。
有一些编译器扩展允许部分特化,但在这种情况下代码失去了可移植性!
关于C++ 函数模板部分特化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8061456/