类模板的 部分定制(partial specializations) 和 定制成员(specialization members)
本文地址: http://blog.csdn.net/caroline_wendy/article/details/17258777
类模板的部分定制, 是指使用类模板的类型(T), 但是不同种类, 如左值, 右值等;
类模板的部分定制, 和类模板定制相同, 都需要类名相同,参数相同;
定制的形参(parameter)比原始模板(original template)更加匹配;
类模板有部分定制, 但函数模板没有, 函数模板只能是重载;
类模板的定制成员, 类模板可以单独定制成员类型, 使不同的实例化类, 使用定制的成员;
代码(部分定制):
/*
* 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; //原始版本
mc.print();
myclass<decltype(ri)> mcl; //左值版本
mcl.print();
myclass<decltype(std::move(i))> mcr; //右值版本
mcr.print();
return 0;
}
输出:
myclass!
myclass! lvalue
myclass! rvalue
代码(定制成员):
/*
* 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; }
};
//定制成员的int版本
template<>
void myclass<int>::print()
{
std::cout << "myclass! int" << std::endl;
}
int main(void)
{
myclass<double> mcd;
mcd.print();
myclass <int> mci;
mci.print();
return 0;
}
输出:
myclass!
myclass! int