类模板的部门定制, 是指利用类模板的范例(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
作者:csdn博客 Spike_King
