模板參數能夠是某些類型或者非類型。類型參數需用使用typename或class關鍵字才指定。ios
以下:數組
template<typename T1,typename T2,...> class className{...}spa
template<class T1, class T2,...> class className{...}code
非類型的參數就是一般的參數定義,表示模板在實例化時所是用的常量。get
仍是以數組模板類爲例子:io
#include <iostream> using namespace std; template <typename T = int, int len = 10> class Array { public: Array(); ~Array(); int length() const { return m_length; } T& get(int index) const; T operator[](int index); private: T *p_array; int m_length; }; template <typename T,int len> Array<T,len>::Array(): p_array(new T[len]), m_length(len) { } template <typename T,int len> Array<T,len>::~Array() { delete p_array; } template <typename T,int len> T& Array<T,len>::get(int index) const { if (index > m_length -1) { throw "ERROR:index is out!"; } else { return p_array[index]; } } template <typename T,int len> T Array<T,len>::operator[](int index) { return p_array[index]; } int main() { Array<> intArr; cout << "the length of int array is " << intArr.length() << '\n'; try { intArr.get(11); }catch(const char *ex) { cout << ex << '\n'; } Array<char> charArr; Array<char,20> char20Arr; cout << "the length of char20 array is " << char20Arr.length() << '\n'; return 0; }