#include"stack1.hpp" // partial specialization of class Stack<> for pointers: template<typename T> classStack<T*> { Private: std::vector<T*> elems; // elements public: voidpush(T*); // push element T* pop(); // pop element T* top()const; // return top element boolempty()const; };
// partial specialization: both template parameters have same type template<typename T> classMyClass<T,T> { … }; // partial specialization: second type is int template<typename T> classMyClass<T,int> { … }; // partial specialization: both template parameters are pointer types template<typename T1, typename T2> classMyClass<T1*,T2*> { … };
template<typename T, typename Cont = std::vector<T>> class Stack { private: Cont elems; // elements public: voidpush(T const& elem); // push element voidpop(); // pop element T const& top()const; // return top element boolempty()const{ // return whether the stack is empty return elems.empty(); } };
类型别名
使用关键字typedef
typedef Stack<int> IntStack; // typedef
使用关键字using
using IntStack = Stack <int>; // alias declaration
类型推导
C++17之后,使用类模板时不一定需要显示指出所有的模版参数的类型了:
1 2 3
Stack< int> intStack1; // stack of strings Stack< int> intStack2 = intStack1; // OK in all versions Stack intStack3 = intStack1; // OK since C++17