C++ 函数模板部分特化?

标签 c++ templates template-specialization partial-specialization

我知道下面的代码是一个类的部分特化:

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/

相关文章:

C++抽象模板类

d - 具有相同类型参数的可变参数模板函数

c++ - 从二进制文件中提取变量名?

c++ - 如何确定一个模板参数可以转换成算术类型?

c++ - 启动时强制连接尚不可见的 QML 项的信号/槽

C++ 如何在 shared_ptr vector 中存储多种类型?

c++ - ToString<T> 好的做法?

C++ SFINAE 部分特化

c++ - 具有相同名称的多个类导致 vtable 问题

c++ - Opencv cv::waitKey() 返回值