格式
template <typename T, ...>
class name
{
}
实例化类模板的时候,必须要有类的全部信息,包括类模板中成员函数的函数体;
//vector实现
template<typename T>
class my_vector
{
public:
typedef T* iter; //迭代器
public:
my_vector();
//在类模板内部使用模板名并不需要提供模板参数;也可以加
my_vector& operator=(const my_vector&);
//my_vector<T>& operator=(const my_vector<T>&);
iter begin();
iter end();
void func();
};
template<typename T>
void my_vector<T>::func()
{
return;
}
//构造函数
template<typename T>
my_vector<T>::my_vector()
{
}
template<typename T>
my_vector<T>& my_vector<T>::operator=(const my_vector<T>&)
{
return *this;
}
int main()
{
my_vector<int> i_vec;
return 0;
}
template<typename T, int size = 10>
class Arr
{
private:
T arr[size];
public:
void func();
};
template<typename T, int size>
void Arr<T, size>::func()
{
cout << size << endl;
return;
}
int main()
{
Arr<int, 100> a;
Arr<int> b;
return 0;
}
原文:https://www.cnblogs.com/Trevo/p/13424791.html