转载:https://www.jianshu.com/p/b56d59f77d53
1.特化
容器Array不能满足主模板中有puck_back的要求,只能特化
// 全特化
template<>
struct Stack<int*, Array>
{
...
};
// 偏特化
template<typename T>
struct Stack<T, Array>
{
...
};
/* 要求:
* 约束一致:
* 尖括号中的参数不能多也不能少,且顺序不能颠倒,
* 而且第二个参数模板Array的定义必须和主模板中对Container的模板约束一致
* 实现可以不一致
* 只需要其签名(模板名和模板参数)和主模板保持一致,而对于其实现,
* 和主模板以及其它特化版本的实现没有任何关系,完全可以根据该特化版本的需要进行定制
*
* 特化最后再提一个我们后面会用到的知识点,那就是模板可以被嵌套地定义在一个类中或模板中,
* 但是模板的特化不可以
*
* 匹配符合度最高的
* 上例中如论是Stack<int, Array>还是Stack<double, Array>都会匹配
* template<typename T> struct Stack<T, Array>版本的实现,而Stack<int, std::list>则会匹配主
* 模板的实现
*/
2.计算
// 数值计算,编译期得到答案,不重要,会产生时间消耗
template<int X, int Y>
struct Caculate
{
enum // 定义成员变量
{
Sum = X + Y,
Dec = X - Y,
Mul = X * Y,
Div = X / Y
};
};
Caculate<10, 2>::Sum,Caculate<10, 2>::Dec,Caculate<10, 2>::Mul,Caculate<10, 2>::Div
// 分别获得10和2的加减乘除的结果
// 类型计算
template<typename T>
struct PointerOf
{
typedef T* Type; // 定义模板,是这个模版自己的类型
};
// using关键字来专门定义类型别名,即代替typedef
template<typename T>
struct PointerOf
{
using Type = T*;
};
PointerOf<const char>::Type s = "Hello world!";
std::cout << s << std::endl;
3.模板递归
template<int N>
struct Factorial
{
enum { Value = N * Factorial<N - 1>::Value };
};
template<>
struct Factorial<1>
{
enum { Value = 1 };
};