類模板支援部分特化(針對型別分類如左值/右值/指標),函數模板僅支援完全特化。部分特化需與原始模板同名、參數數量相同,但參數型別更具體(更匹配)。
/*
* CppPrimer.cpp - 類模板部分特化範例
* Created on: 2013.12.9
* Author: Caroline
* eclipse cdt, gcc 4.8.1
*/
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
// 原始模板
template<typename T>
struct myclass {
void print() { std::cout << "myclass!" << std::endl; }
};
// 部分特化:左值引用
template<typename T>
struct myclass<T&> {
void print() { std::cout << "myclass! lvalue" << std::endl; }
};
// 部分特化:右值引用
template<typename T>
struct myclass<T&&> {
void print() { std::cout << "myclass! rvalue" << std::endl; }
};
int main(void) {
int i(1988);
int& ri = i;
myclass<decltype(1988)> mc; // 原始版本:int
mc.print();
myclass<decltype(ri)> mcl; // 左值版本:int&
mcl.print();
myclass<decltype(std::move(i))> mcr; // 右值版本:int&&
mcr.print();
return 0;
}
myclass! myclass! lvalue myclass! rvalue
類模板可單獨特化特定成員函數,使不同實例化類別使用特化版本:
template <typename T>
class Widget {
public:
void process() { /* 通用實作 */ }
};
// 特化 int 版本的 process
template <>
void Widget<int>::process() {
std::cout << "int specialized process" << std::endl;
}
T& 比 T 具體)template<> void Class<T>::func()template<> class Class<int>,所有參數固定