目录
模板(template)
泛型,是一种将类型参数化以达到代码复用的技术,C++中使用模板来实现泛型
模板的使用格式如下
template <typename\class T>
typename和class是等价的
模板没有被使用时,是不会被实例化出来的
模板的声明和实现如果分离到.h和.cpp中,会导致链接错误
一般将模板的声明和实现统一放到一个.hpp文件中
函数模板
template <class T>
void swapValues(T &v1,T &v2){
T temp = v1;
v1 = v2;
v2 = temp;
}
void templateTest(){
int a = 10;
int b = 20;
swapValues<int>(a, b);
cout<<"a = "<<a<<endl<<"b = "<<b<<endl;
swapValues(a, b);
cout<<"a = "<<a<<endl<<"b = "<<b<<endl;
}
多参数模板
template <class T1,class T2>
void display(const T1& v1, const T2& v2){
std::cout<<"v1 = "<<v1<<std::endl<<"v2 = "<<v2<<std::endl;
}
void templateTest2(){
int a = 10;
double b = 2.5;
display<int,double>(a, b);
display(a, b);
}
类模板
template <class Item>
class Array{
//加上特化处理,重载需添加template<class T>,否则无法运行
template<class T>
friend ostream& operator<<(ostream & cout, const Array<T> &value);
int m_size = 0;
int m_capacity = 0;
Item * m_data = nullptr;
public:
Array(int capacity);
~Array();
int size();
Item get(int index);
Item operator[](int index);
void add(Item value);
void display();
};
template <class Item>
Array<Item>::Array(int capacity){
if (capacity<=0) {return;}
this->m_capacity = capacity;
//申请Item*capacity大小的空间并初始化为0
this->m_data = new Item[capacity]{};
}
template <class Item>
Array<Item>::~Array(){
if (this->m_data) {
this->m_capacity = 0;
this->m_size = 0;
delete [] this->m_data;
this->m_data = nullptr;
}
}
template <class Item>
int Array<Item>::size(){
return this->m_size;
}
template <class Item>
Item Array<Item>::get(int index){
if (index<0 || index>= this->m_size) {
return 0;
}
return this->m_data[index];
}
template <class Item>
Item Array<Item>::operator[](int index){
return get(index);
}
template<class Item>
void Array<Item>::add(Item value){
if (this->m_size == this->m_capacity) {
std::cout<<"数组已满"<<std::endl;
return;
}
m_data[m_size++] = value;
}
template<class Item>
void Array<Item>::display(){
std::cout<<"[";
for (int i =0; i<m_size; i++) {
std::cout<<m_data[i];
if (i != m_size-1) {
std::cout<<", ";
}
}
std::cout<<"]"<<std::endl;
}
/**
参考文章
模板类友元函数和运算符重载
https://blog.csdn.net/liubowen920711/article/details/75578910?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param
*/
template <class T>
ostream& operator<<(ostream &cout, const Array<T> &array) {
std::cout << "[";
for (int i = 0; i < array.m_size; i++) {
std::cout << array.m_data[i];
if (i != array.m_size - 1) {
std::cout << ", ";
}
}
return std::cout << "]";
}
void template3(){
Array<int> array(3);
array.add(1);
array.add(2);
array.add(3);
array.display();
cout<<array<<endl;
}
行者常至,为者常成!