【C++基础】模板
一、模板
1、模板的概念
模板就是建立通用的模具,大大提高复用性
模板的特点:
- 模板不可以直接使用,它只是一个框架
- 模板的通用并不是万能的
二、函数模板
- C++另一种编程思想称为
泛型编程
,主要利用的技术就是模板 - C++提供两种模板机制:
函数模板
和类模板
1、函数模板语法
函数模板的作用:
建立一个通用函数,其函数返回值类型和形参类型可以不具体制定,用一个虚拟的类型来代表。
语法:template<typename T>
函数声明或定义
解释:
template —— 声明创建模板
typename —— 表明其后面的符号是一种数据类型,可以用class代替
T —— 通用的数据类型,名称可以替换,通常为大写字母
示例:
#include<iostream>
using namespace std;
//函数模板
template<typename T>
void mySwap(T& a, T& b)
{
T temp = a;
a = b;
b = temp;
}
int main()
{
int a = 1;
int b = 20;
//1、自动类型推导
mySwap(a, b);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
double c = 1.1;
double d = 22.22;
//2、显示指定类型
mySwap<double>(c, d);
cout << "c = " << c << endl;
cout << "d = " << d << endl;
}
总结:
- 函数模板利用关键字
template
- 使用函数模板有两种方式:
自动类型推导
、显示指定类型
- 模板的目的是为了提高复用性,将类型参数化
2、函数模板注意事项
注意事项:
- 自动类型推导,必须推导出一致的数据类型T,才可以使用
- 模板必须要确定出T的数据类型,才可以使用
示例:
1、自动类型推导,必须推导出一致的数据类型T,才可以使用
数据类型不一致,报错。
2、 模板必须要确定出T的数据类型,才可以使用
编译器无法推导出数据类型,报错
解决办法:
显示指定类型
3、函数模板案例
案例描述:
- 利用函数模板封装一个排序函数,可以对不同数据类型数组进行排序
- 排序规则从大到小,排序算法为选择排序
- 分别利用char数组和int数组进行测试
示例:
#include<iostream>
using namespace std;
//交换模板
template<class T>
void mySwap(T& a, T& b)
{
T temp = a;
a = b;
b = temp;
}
//排序模板
template<class T>
void mySort(T arr[], int len)
{
for (int i = 0; i < len; i++)
{
int max = i;
for (int j = i +1; j < len; j++)
{
if (arr[max] < arr[j])
{
max = j;
}
}
if (max != i)
{
mySwap(arr[max],arr[i]);
}
}
}
//打印模板
template<class T>
void myPrint(T arr[], int len)
{
for (int i = 0; i < len; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
int main()
{
//测试字符排序
char charArr[] = "beadcf";
int num = sizeof(charArr) / sizeof(char);
mySort(charArr, num);
myPrint(charArr,num);
//测试数组排序
int intArr[] = { 2,1,4,8,7,3,9,6};
int num1 = sizeof(intArr) / sizeof(int);
mySort(intArr, num1);
myPrint(intArr, num1);
}
4、普通函数与函数模板的区别
普通函数与函数模板的区别:
- 普通函数调用时可以发生自动类型转换(隐式类型转换)
- 函数模板调用时,如果利用自动类型推导,不会发生隐式类型转换
- 如果利用显示指定类型的方式,可以发生隐式类型转换
示例:
#include<iostream>
using namespace std;
//普通函数模板
int myAdd(int a, int b)
{
return a + b;
}
//函数模板
template<class T>
T myAdd1(T a, T b)
{
return a + b;
}
int main()
{
int a = 1;
int b = 2;
char c = 'c';
cout << myAdd(a, c) << endl;
//自动类型推导,不会发生隐式类型转换
//cout << myAdd1(a, c) << endl;
//显示类型推导,会发生隐式类型转换
cout << myAdd1<int>(a, c) << endl;
}
总结:建议使用显示指定类型的方式,调用函数模板,因为可以自己确定通用类型T
5、通用函数与函数模板的调用规则
调用规则如下:
- 如果函数模板和普通函数都可以实现,优先调用普通函数
- 可以通过空模板参数列表来强制调用函数模板
- 函数模板也可以发生重载
- 如果函数模板可以产生更好的匹配,优先调用函数模板
示例:
#include<iostream>
using namespace std;
void myPrint(int a)
{
cout << "调用 普通 函数" << endl;
}
template<class T>
void myPrint(T a)
{
cout << "调用 模板 函数" << endl;
}
//3. 函数模板也可以发生重载
template<class T>
void myPrint(T a,T b)
{
cout << "调用 重载-模板 函数" << endl;
}
int main()
{
int a = 1;
int b = 2;
char c = 'c';
//1. 如果函数模板和普通函数都可以实现,优先调用普通函数
cout << "myPrint(a):";
myPrint(a);
// 2. 可以通过空模板参数列表来强制调用函数模板
cout << "myPrint<>(a):";
myPrint<>(a);
//3. 调用重载模板
cout << "myPrint<>(a, b):";
myPrint<>(a, b);
//4. 如果函数模板可以产生更好的匹配,优先调用函数模板
cout << "myPrint(c):";
myPrint(c);
}
总结:既然提供了函数模板,就不要提供普通函数,否则容易出现二义性
6、模板的局限性
局限性:
- 模板的通用性并不是万能的
示例:
#include<iostream>
using namespace std;
template<class T>
void myPrint(T a, int num)
{
for (int i = 0; i < num; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
template<class T>
void func(T a,T b)
{
a = b;
myPrint(a, 2);
}
int main()
{
int arr1[2] = { 10,20 };
int arr2[2] = { 1,2 };
func(arr1, arr2);
int num = sizeof(arr1) / sizeof(int);
myPrint(arr1, num);
}
输出:
func模板内数组a被赋值了
而在模板外数组a并没有变化
话说传进func模板函数的不是数组地址吗?为啥会出现这种情况。
好怪,传入模板的数组被赋值了。
看看指针
代码:
#include<iostream>
using namespace std;
template<class T>
void myPrint(T a, int num)
{
for (int i = 0; i < num; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
template<class T>
void func(T a,T b)
{
cout <<"a = " << a << "\t" << "b = " << b << endl;
a = b;
myPrint(a, 2);
cout << "a = " << a << "\t" << "b = " << b << endl;
}
int main()
{
int arr1[2] = { 10,20 };
int arr2[2] = { 1,2 };
func(arr1, arr2);
}
输出:
再函数模板内a的指针指向了b的指针指向的地址(太绕了,简单讲就是,将b赋值给了a)。
讲道理不应该这样的,不过赋值的只有模板内,模板外a并没有被赋值。
所以,看起来就是模板不能给数组提供赋值操作。
如果把数组换成自定义类的话,是一定会报错的。
#include<iostream>
using namespace std;
class Student
{
public:
string name;
int age;
Student(string name, int age)
{
this->name = name;
this->age = age;
}
};
//进行比较
template<class T>
bool myCompare(T& a, T& b)
{
if (a > b)
{
return true;
}
else
{
return false;
}
}
int main()
{
Student s1("张三",10);
Student s2("李四",20);
cout << "s1 > s2 = " << myCompare(s1, s2) << endl;
}
报错:
因为编译器不知道你的自定义类型怎么进行比较。
解决方案(两种)
第一种:重载
在Student类中重载>
符号
bool operator>(Student s)
{
if (this->age > s.age)
{
return true;
}
else
{
return false;
}
}
输出:
第二种:为特定的类型提供具体化的模板
利用具体化优选调用的规则
#include<iostream>
using namespace std;
class Student
{
public:
string name;
int age;
Student(string name, int age)
{
this->name = name;
this->age = age;
}
};
//进行比较
template<class T>
bool myCompare(T& a, T& b)
{
if (a > b)
{
return true;
}
else
{
return false;
}
}
template<> bool myCompare(Student& a, Student& b)
{
if (a.age > b.age)
{
return true;
}
else
{
return false;
}
}
int main()
{
Student s1("张三",30);
Student s2("李四",20);
cout << "s1 > s2 = " << myCompare(s1, s2) << endl;
}
输出:
输出正确
总结:
- 利用具体化的模板,可以解决自定义类型的通用化
- 学习模板并不是为了写模板,而是在STL能够运用系统提供的模板
三、类的模板
类模板的作用:
- 建立一个通用类,类中的成员、数据类型可以不计提制定,用一个虚拟的类型来代表。
1、类模板语法:
template<typename T>
类
解释:
template —— 声明创建模板
typename —— 表明其后面的符号是一种数据类型,可以用class代替
T —— 统用的数据类型,名称可以替换,通常为大写字母
示例:
#include<iostream>
using namespace std;
// 类模板
template<class NameType, class AgeType>
class Student
{
public:
Student(NameType name, AgeType age)
{
this->name = name;
this->age = age;
}
NameType name;
AgeType age;
void showInfor()
{
cout << "姓名:" << this->name << "\t年龄:" << this->age << endl;
}
};
int main()
{
Student<string, int> s1("张三", 10);
s1.showInfor();
}
输出:
总结:类模板和函数模板语法相似,在声明模板template后面加类,此类称为模板。
2、类模板与函数模板的区别
类模板与函数模板区别主要有两点:
- 类模板没有自动类型推导的使用方式
- 类模板在模板参数列表中可以有默认参数
示例:
#include<iostream>
using namespace std;
// 类模板
//类模板在模板参数列表中可以有默认参数
template<class NameType, class AgeType = int>
class Student
{
public:
Student(NameType name, AgeType age)
{
this->name = name;
this->age = age;
}
NameType name;
AgeType age;
void showInfor()
{
cout << "姓名:" << this->name << "\t年龄:" << this->age << endl;
}
};
int main()
{
//模板中第二个参数有默认类型,所以可以省略定义第二个参数类型
Student<string> s1("张三", 10);
s1.showInfor();
}
输出:
总结:
- 类模板使用只能用显示指定类型的方式
- 类模板中的模板参数列表可以有默认参数
3、类模板中成员函数创建时机
类模板中成员函数和普通类中成员函数创建时机是有区别的:
- 普通类中的成员函数一开始就可以创建
- 类模板中的成员函数在调用时才创建
示例:
#include<iostream>
using namespace std;
class Student1
{
public:
void showStudent1()
{
cout << "show Student1" << endl;
}
};
class Student2
{
public:
void showStudent2()
{
cout << "show Student2" << endl;
}
};
template<class T>
class MyClass
{
public:
T obj;
//类模板中的成员函数,并不是一开始就创建的,而是在模板调用时再生成
void func1()
{
obj.showStudent1();
}
void func2()
{
obj.showStudent2();
}
};
int main()
{
MyClass<Student1>m;
m.func1();
//m.func2(); 编译出错,说明函数调用才会去创建成员函数
}
输出:
总结:类模板中的成员函数并不是一开始就创建的,而是在调用时才创建
4、类模板中成员函数类外实现
目标:类模板实例化的对象,向函数传参的方式
三种传入方式:
- 指定传入的类型:直接显示对象的数据类型
- 参数模板化:将对象中的参数变为模板进行传递
- 整个类模板化:将这个对象类型模板化进行传递
示例:
#include<iostream>
using namespace std;
// 三种传入方式:
template<class T1,class T2>
class Student
{
public:
Student(T1 name, T2 age)
{
this->name = name;
this->age = age;
}
void showStudnet()
{
cout << "姓名:" << this->name << "\t年龄:" << this->age << endl;
}
T1 name;
T2 age;
};
//1. 指定传入的类型: 直接显示对象的数据类型
void printTest01(Student<string, int>&s)
{
s.showStudnet();
}
void test01()
{
Student<string, int>s("张三", 10);
printTest01(s);
}
//2. 参数模板化: 将对象中的参数变为模板进行传递
template<class T1, class T2>
void printTest02(Student<T1, T2>&s)
{
s.showStudnet();
}
void test02()
{
Student<string, int>s("李四", 20);
printTest02(s);
}
//3. 整个类模板化: 将这个对象类型模板化进行传递
template<class T>
void printTest03(T &s)
{
s.showStudnet();
}
void test03()
{
Student<string, int>s("王五", 30);
printTest03(s);
}
int main()
{
test01();
test02();
test03();
}
输出:
总结:
- 通过类模板创建对象,可以有三种方式向函数中进行传参
- 使用比较广泛是第一种:指定传入的类型
5、类模板与继承
当类模板碰到继承时,需要注意一下几点
- 当子类继承的父类是一个类模板时,子类在声明的时候,要指定出父类中T的类型
- 如果不指定,编译器无法给子类分配内存
- 如果想灵活指定出父类中T的类型,子类也需要变为模板
示例:
#include<iostream>
using namespace std;
template<class T>
class Base
{
T m;
};
//必须指定父类中的T的类型,才能继承
class Son :public Base<int>
{
};
//如果想灵活指定父类中T类型,子类也需要变类模板
template<class T1, class T2>
class Son2 :public Base<T2>
{
public:
Son2()
{
cout << "T1的类型为:" << typeid(T1).name() << endl;
cout << "T2的类型为:" << typeid(T2).name() << endl;
}
T1 obj;
};
int main()
{
Son s1;
//类实例化时,要用显示类型。
Son2<int, char> s2;
}
注:必须指定出父类中T的类型,不能用隐式转换。
总结:如果父类是类模板,子类需要指定出父类的数据类型
6、类模板成员函数类外实现
示例:
#include<iostream>
using namespace std;
template<class T1, class T2>
class Student
{
public:
Student(T1 name, T2 age);
void showStudent();
T1 name;
T2 age;
};
//构造函数类外实现
template<class T1, class T2>
Student<T1, T2>::Student(T1 name, T2 age)
{
this->name = name;
this->age = age;
}
//函数类外实现
template<class T1, class T2>
void Student<T1, T2>::showStudent()
{
cout << "name: " << this->name << "\tage: " << this->age << endl;
}
int main()
{
Student<string, int> s("张三", 10);
s.showStudent();
}
输出:
总结:类模板中成员函数类外实现时,需要加上模板参数列表
7、类模板分文件编写
难点:
- 类模板中成员函数创建时机是在调用阶段(因为在调用前模板的数据类型没有确定,所以不能创建),导致分文件编写时链接不到
解决办法:
- 直接包含
.cpp
源文件- 将声明和实现写到同一文件中,并更改后缀名为
.hpp
,hpp
是约定的名称
示例:
办法1:直接包含.cpp
源文件
student.h文件
#pragma once
#include<iostream>
using namespace std;
template<class T1, class T2>
class Student
{
public:
Student(T1 name, T2 age);
void showStudent();
T1 name;
T2 age;
};
student.cpp文件
#include "student.h"
template<class T1, class T2>
Student<T1, T2>::Student(T1 name, T2 age)
{
this->name = name;
this->age = age;
}
template<class T1, class T2>
void Student<T1, T2>::showStudent()
{
cout << "name: " << this->name << "\tage: " << this->age << endl;
}
源文件
#include<iostream>
using namespace std;
#include "student.cpp"
int main()
{
Student<string, int> s("张三", 10);
s.showStudent();
}
办法2:将声明和实现写到同一文件中,并更改后缀名为.hpp
,hpp
是约定的名称
student.hpp文件
#pragma once
#include<iostream>
using namespace std;
template<class T1, class T2>
class Student
{
public:
Student(T1 name, T2 age);
void showStudent();
T1 name;
T2 age;
};
template<class T1, class T2>
Student<T1, T2>::Student(T1 name, T2 age)
{
this->name = name;
this->age = age;
}
template<class T1, class T2>
void Student<T1, T2>::showStudent()
{
cout << "name: " << this->name << "\tage: " << this->age << endl;
}
源文件
#include<iostream>
using namespace std;
#include "student.hpp"
int main()
{
Student<string, int> s("张三", 10);
s.showStudent();
}
总结:主流的解决方式是第二种,将类模板成员函数写到一起,并将后缀名改为.hpp
8、类模板与友元
目标:类模板配合友元函数的类内和类外实现
全局函数类内实现 - 直接在类内声明友元即可
全局函数类外实现 - 需要提前让编译器知道全局函数的存在
示例:
#include<iostream>
using namespace std;
template<class T1, class T2>
class Student;
template<class T1, class T2>
void showStudent2(Student<T1, T2>s)
{
cout << "类外实现:" << endl;
cout << "name: " << s.name << "\tage: " << s.age << endl;
}
template<class T1, class T2>
class Student
{
//1全局函数,类内实现
friend void showStudent1(Student<T1, T2>s)
{
cout << "类内实现:" << endl;
cout << "name: " << s.name << "\tage: " << s.age << endl;
}
//2全局函数,类外实现
//加空模板参数列表,表明这是一个模板函数
//如果全局函数是类外实现,需要让编译器提前知道这个函数的存在
friend void showStudent2<>(Student<T1, T2> s);
public:
Student(T1 name, T2 age)
{
this->name = name;
this->age = age;
}
private:
T1 name;
T2 age;
};
int main()
{
Student<string, int> s("张三", 10);
showStudent1(s);
showStudent2(s);
}
总结:建议全局函数做类内实现,用法简单,而且编译器可以直接识别
9、类模板案例
实现一个通用数组:
- 可以对内置数据类型以及自定义数据类型的数据进行存储
- 将数组中的数据存储到堆区
- 构造函数中可以传入数组的容量
- 提供对应的拷贝构造函数以及operator=防止浅拷贝问题
- 提供尾插法和尾删法对数组中的数据进行增加和删除。
- 可以通过下标的方式访问数组中的元素。
- 可以获取数组中当前元素个数和数组的容量
示例
MyArray.hpp
#pragma once
#include<iostream>
using namespace std;
template<class T>
class MyArray
{
public:
//有参构造 参数:容量
MyArray(int capacity)
{
this->m_Capacity = capacity;
this->m_Size = 0;
this->pAddress = new T[this->m_Capacity];
}
//拷贝构造函数
MyArray(const MyArray& arr)
{
this->m_Capacity = arr.m_Capacity;
this->m_Size = arr.m_Size;
//深拷贝
this->pAddress = new T[arr.m_Capacity];
for (int i = 0; i < this->m_Size; i++)
{
this->pAddress[i] = arr.pAddress[i];
}
}
//重载运算符,防止浅拷贝问题
MyArray& operator=(const MyArray& arr)
{
if (this->pAddress != NULL)
{
delete[] this->pAddress;
this->pAddress = NULL;
this->m_Capacity = 0;
this->m_Size = 0;
}
//深拷贝
this->m_Capacity = arr.m_Capacity;
this->m_Size = arr.m_Size;
this->pAddress = new T[arr.m_Capacity];
for (int i = 0; i < this->m_Size; i++)
{
this->pAddress[i] = arr.pAddress[i];
}
return *this;
}
//尾插法
void Push_Back(const T& val)
{
//判断容量是否满了
if (this->m_Capacity == this->m_Size)
{
cout << "已经满了,不能在插了。" << endl;
return;
}
this->pAddress[this->m_Size] = val;
this->m_Size++;
}
//尾删法
void Pop_Back()
{
//让用户访问不到最后一个元素,即为尾删,逻辑删除
if (this->m_Size == 0)
{
cout << "数据为空,无法删除。" << endl;
return;
}
this->m_Size--;
}
//通过下标方式访问数组中的元素
T& operator[](int index)
{
return this->pAddress[index];
}
//返回数组容量
int getCapacity()
{
return this->m_Capacity;
}
//返回数组大小
int getSize()
{
return this->m_Size;
}
//析构函数
~MyArray()
{
if (this->pAddress != NULL)
{
delete[] this->pAddress;
this->pAddress = NULL;
}
}
private:
//数组指针
T* pAddress;
//数组容量
int m_Capacity;
// 数组大小
int m_Size;
};
源文件
#include<iostream>
using namespace std;
#include "MyArray.hpp"
class Student
{
public:
Student() {};
Student(string name, int age)
{
this->name = name;
this->age = age;
}
void showStudnet()
{
cout << "name: " << this->name << "\tage:" << this->age << endl;
}
private:
string name;
int age;
};
int main()
{
MyArray<Student>m(5);
Student s1("张三",10);
Student s2("李四",20);
Student s3("王五",30);
Student s4("赵六",40);
Student s5("陈七",50);
Student s6("周八",60);
m.Pop_Back();
m.Push_Back(s1);
m.Push_Back(s2);
m.Push_Back(s3);
m.Push_Back(s4);
cout << m.getSize() << endl;
m.Push_Back(s5);
m.Push_Back(s6);
m[1].showStudnet();
}