1 模板
时间:2023-10-18 23:33 作者:wen 分类: C++
[toc]
模板
- 本阶段主要针对C++泛型编程和STL技术做详细讲解,探讨C++更深层的使用
模板的概念
模板就是建立通用的模具,大大提高复用性
模板的特点:
- 模板不可以直接使用,它只是一个框架
- 模板的通用并不是万能的
模板函数
- C++另一个编程思想称为泛型编程,主要利用的技术就是模板
- C++提供两种模板机制,函数模板和类模板
函数模板的语法
函数模板作用:
建立一个通用的函数,其函数返回值类型和形参类似可以不具体制定,用一个虚拟的类型来代表。
语法:
template<typename T>
函数声明或定义
解释:
template --- 声明创建模板
typename --- 表明其后面的符号是一种数据类型,可以用class代替
T --- 通用的数据类型,名称可以替换,通常为答谢字母
案例:
#include <iostream>
#include <string>
using namespace std;
// 函数模板
// 两个数交换函数
template<typename T>
void myswap(T& a, T& b)
{
T temp = a;
a = b;
b = temp;
}
void testA()
{
int a = 10;
int b = 20;
// 利用函数模板交换
// 两种方式使用函数模板
// 1.自动类型推导
//myswap(a, b);
// 2.显示指定类型
myswap<int>(a, b);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
int main()
{
testA();
system("pause");
return 0;
}
总结:
- 函数模板利用关键字template
- 使用函数模板有两种方式:自动类型推导、显示指定类型
- 模板的目的是为了提高复用性,将类型参数化
函数模板注意事项
注意事项:
- 自动类型推导,必须推导出一致的数据类型T,才可以使用
- 模板必须要确定出T的数据类型,才可以使用
示例:
#include <iostream>
#include <string>
using namespace std;
// 函数模板
// 两个数交换函数
template<class T>
void myswap(T& a, T& b)
{
T temp = a;
a = b;
b = temp;
}
//自动类型推导,必须推导出一致的数据类型T,才可以使用
void testA()
{
int a = 10;
int b = 20;
char c = 'c';
myswap(a, b); // 正确
//myswap(a, c); // 错误!推导不出一致的数据类型
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
template<class T>
void func()
{
cout << "func 调用" << endl;
}
// 模板必须要确定出T的数据类型,才可以使用
void testB()
{
//func(); // 错误, 不能确定T的数据类型
func<int>();
}
int main()
{
testA();
testB();
system("pause");
return 0;
}
函数模板案例
案例描述:
- 利用函数模板封装一个排序的函数,可以对不同数据类型数组进行排序
- 排序规则从大到小,排序算法为选择排序
- 分别利用char数组和int数组进行测试
示例:
#include <iostream>
#include <string>
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<typename T>
void myPrint(T arr[], int len)
{
for (int i = 0; i < len; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
void testA()
{
//测试char数组
char charArr[] = "badcfe";
mySort(charArr, sizeof(charArr));
myPrint(charArr, sizeof(charArr));
// 测试int数组
int intArr[] = { 7,5,1,3,9,2,4,6,8 };
int len = sizeof(intArr) / sizeof(int);
mySort(intArr, len);
myPrint(intArr, len);
}
int main()
{
testA();
system("pause");
return 0;
}
普通函数与函数模板的区别
普通函数与函数模板的区别:
- 普通函数调用是可以发生自动类型转换(隐士类型转换)
- 函数模板调用是,如果利用自动类型推导,不会发生隐士类型转换
- 如果利用显示指定类型的方式,可以发生隐士类型转换
示例:
#include <iostream>
#include <string>
using namespace std;
// 普通函数
int myAdd01(int a, int b)
{
return a + b;
}
// 函数模板
template<class T>
T myAdd02(T a, T b)
{
return a + b;
}
void testA()
{
int a = 10;
int b = 20;
char c = 'c';
cout << myAdd01(a, b) << endl;
cout << myAdd01(a, c) << endl; // 发生了隐士类型转换, c=99
// 自动类型推导
cout << myAdd02(a, b) << endl;
//cout << myAdd02(a, c) << endl; // 编译错误, 不能发生隐士类型转换
// 显示指定类型
cout << myAdd02<int>(a, c) << endl; // 可以发生隐士类型转换
}
int main()
{
testA();
system("pause");
return 0;
}
普通函数与函数模板的调用规则
调用规则如下:
- 如果函数模板和普通函数都可以实现,优先调用普通函数
- 可以通过空模板参数列表来强制调用函数模板
- 函数模板也可以发送重载
- 如果函数模板可以产生更好的匹配,优先调用函数模板
示例:
#include <iostream>
#include <string>
using namespace std;
// 普通函数
void myPrint(int a, int b)
{
cout << "调用的普通函数" << endl;
}
//如果声明函数没有写函数体,也会优先调用,编译会报错
//void myPrint(int a, int b);
// 函数模板
template<class T>
void myPrint(T a, T b)
{
cout << "调用的函数模板" << endl;
}
template<class T>
void myPrint(T a, T b, T c)
{
cout << "调用的函数模板" << endl;
}
void testA()
{
int a = 10;
int b = 20;
int c = 30;
myPrint(a, b); // 如果函数模板和普通函数都可以实现,优先调用普通函数
myPrint<>(a, b); // 通过空模板参数列表来强制调用函数模板
myPrint(a, b, c); // 函数模板也可以发送重载
//如果函数模板可以产生更好的匹配,优先调用函数模板
char c1 = 'a';
char c2 = 'b';
myPrint(c1, c2);
}
int main()
{
testA();
system("pause");
return 0;
}
总结:既然提供了函数模板,最好就不要提供普通函数,否则容易出现二义性
模板的局限性
局限性:
- 模板的通用性并不是万能的
例如:
template<class T>
void f(T a, T b)
{
a = b;
}
在上述代码中提供的赋值操作,如果传入的a和b是一个数组,就无法实现了
再例如:
template<class T>
void f(T a, T b)
{
if (a > b) {
}
}
在上述代码中,如果T的数据类型传入的是像Person这样的自定义数据类型,也无法正常运行
因此C++为了解决这种问题,提供模板的重载,可以为这些特点的类型提供具体化的模板
示例:
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
Person(string name, int age):m_Name(name),m_Age(age) {
}
public:
string m_Name;
int m_Age;
};
template <class T>
bool myCompare(T& a, T& b)
{
if (a == b)
{
return true;
}
else {
return false;
}
}
// 利用具体化Person的版本实现代码,具体化优先调用
template<> bool myCompare(Person& p1, Person& p2)
{
if (p1.m_Name == p2.m_Name && p1.m_Age == p2.m_Age)
{
return true;
}
else {
return false;
}
}
void testA()
{
Person p1("Tom",10);
Person p2 = {"Tom",20};
cout << myCompare(p1, p2) << endl;
}
int main()
{
testA();
system("pause");
return 0;
}
总结:
- 利用具体化的模板,可以解决自定义类型的通用化
- 学习模板并不是为了写模板,而是在STL能够运用系统提供的模板
类模板
类模板语法
类模板作用:
- 建立一个通用类,类中的成员 数据类型可以不具体制定,用一个虚拟类型来代表。
语法:
template<typename T>
类
解释:
template --- 声明创建模板
typename --- 表示其后面的符号是一种数据类型,可以用class代替
T --- 通用的数据类型,名称可以替换,通常为大写字母
示例:
#include <iostream>
#include <string>
using namespace std;
// 类模板
template <class NameType,class AgeType>
class Person
{
public:
Person(NameType name, AgeType age):m_Name(name),m_Age(age) {
}
void showPerson()
{
cout << "姓名:" << this->m_Name << "\t年龄:" << m_Age << endl;
}
public:
NameType m_Name;
AgeType m_Age;
};
void testA()
{
Person<string,int> p1("Tom",10);
p1.showPerson();
Person<string, int> p2 = {"孙悟空", 99};
p2.showPerson();
}
int main()
{
testA();
system("pause");
return 0;
}
类模板与函数模板的区别
类模板与函数模板的区别只要有两点:
- 类模板没有自动类型推导的使用方式
- 类模板在模板参数列表中可以有默认参数
示例:
#include <iostream>
#include <string>
using namespace std;
// 类模板
//2.类模板在模板参数列表中可以有默认参数
template <class NameType,class AgeType = int>
class Person
{
public:
Person(NameType name, AgeType age):m_Name(name),m_Age(age) {
}
void showPerson()
{
cout << "姓名:" << this->m_Name << "\t年龄:" << m_Age << endl;
}
public:
NameType m_Name;
AgeType m_Age;
};
/*
1.类模板没有自动类型推导的使用方式
*/
void testA()
{
//Person p("孙悟空",1000) // 编译错误, 无法自动类型推导
Person<string> p1("猪八戒",999);
p1.showPerson();
}
int main()
{
testA();
system("pause");
return 0;
}
类模板中成员函数创建时机
类模板中成员函数和普通类中成员函数创建时机是有区别的:
- 普通类中的成员函数一开始就可以创建
- 类模板中的成员函数在调用是才创建
示例:
#include <iostream>
#include <string>
using namespace std;
// 类模板中的成员函数的创建时机
class Person1
{
public:
void showPerson1()
{
cout << "show person1" << endl;
}
};
class Person2
{
public:
void showPerson2()
{
cout << "show person1" << endl;
}
};
template <class T>
class MyClass
{
public:
T obj;
void func1()
{
obj.showPerson1();
}
void func2()
{
obj.showPerson2();
}
};
//类模板中的成员函数在调用是才创建
void testA()
{
MyClass<Person1> m;
m.func1();
m.func2(); // 编译出错
}
int main()
{
testA();
system("pause");
return 0;
}
类模板对象做函数参数
学习目标:
- 类模板实例化出的对象,向函数传参的方式
一共三种传入方式:
- 指定传入的类型 --- 直接显示对象的数据类型
- 参数模板化 --- 将对象中的参数变为模板进行传递
- 整个类模板化 --- 将这个对象类型模板化进行传递
示例:
#include <iostream>
#include <string>
using namespace std;
//类模板对象做函数参数
/*
1.指定传入的类型 --- 直接显示对象的数据类型
2.参数模板化 --- 将对象中的参数变为模板进行传递
3.整个类模板化 --- 将这个对象类型模板化进行传递
*/
template<class T1,class T2>
class Person
{
public:
T1 m_Name;
T2 m_Age;
public:
Person(T1 name, T2 age)
{
this->m_Name = name;
this->m_Age = age;
}
void showPerson()
{
cout << "姓名:" << m_Name << "\t年龄:" << m_Age << endl;
}
};
/// <summary>
/// 1.指定传入的类型
/// </summary>
/// <param name="p"></param>
void printPerson1(Person<string, int>& p)
{
p.showPerson();
}
void testA()
{
Person<string, int> p("孙悟空", 1000);
printPerson1(p);
}
/// <summary>
/// 2.参数模板化
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <param name="p"></param>
template<class T1, class T2>
void printPerson2(Person<T1, T2>& p)
{
p.showPerson();
cout << "T1的类型为:" << typeid(T1).name() << endl;
cout << "T2的类型为:" << typeid(T2).name() << endl;
}
void testB()
{
Person<string, int> p("猪八戒", 900);
printPerson2(p);
}
/// <summary>
/// 3.整个类模板化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="p"></param>
template<class T>
void printPerson3(T& p)
{
p.showPerson();
cout << "T的类型为:" << typeid(T).name() << endl;
}
void testC()
{
Person<string, int> p("唐僧", 30);
printPerson3(p);
}
int main()
{
testA();
testB();
testC();
system("pause");
return 0;
}
总结:
- 通过类模板创建的对象,可以有三种方式向函数中进行传参
- 使用比较广泛是第一种:指定传入的类型
类模板与继承
当类模板碰到继承时,需要注意以下几点:
- 当子类继承的父类是一个类模板时,子类再声明的时候,要指定出父类中T的类型
- 如果不指定,编译器无法给子类分配内存
- 如果想灵活指定出父类中T的类型,子类也需要变为类模板
示例:
#include <iostream>
#include <string>
using namespace std;
// 类模板与继承
template <class T>
class Base
{
T m;
};
//class Son : public Base // 错误,必须要知道父类中T的类型,才能继承给子类
class Son : public Base<int>
{
};
void testA()
{
Son s1;
}
//如果想灵活指定出父类中T的类型,子类也需要变为类模板
template<class T1,class T2>
class Son2 :public Base<T2>
{
public:
T1 obj;
Son2()
{
cout << "T1的类型为:" << typeid(T1).name() << endl;
cout << "T2的类型为:" << typeid(T2).name() << endl;
}
};
void testB()
{
Son2<int, char>s2;
}
int main()
{
testA();
testB();
system("pause");
return 0;
}
类模板成员函数类外实现
学习目标:能够掌握类模板中的成员函数类外实现
示例:
#include <iostream>
#include <string>
using namespace std;
//类模板中的成员函数类外实现
template<class T1,class T2>
class Person
{
public:
T1 m_Name;
T2 m_Age;
public:
Person(T1 name, T2 age);
/*{
this->m_Name = name;
this->m_Age = age;
}*/
void showPerson();
/*{
cout << "姓名:" << m_Name << "\t年龄:" << m_Age << endl;
}*/
};
// 构造函数类外实现
template<class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age)
{
this->m_Name = name;
this->m_Age = age;
}
// 成员函数的类外实现
template<class T1, class T2>
void Person<T1,T2>::showPerson()
{
cout << "姓名:" << m_Name << "\t年龄:" << m_Age << endl;
}
void testA()
{
Person<string, int> p("Tom", 20);
p.showPerson();
}
int main()
{
testA();
system("pause");
return 0;
}
总结:类模板中成员函数类外实现,需要加上模板参数列表
类模板分文件编写
学习目标:
- 掌握类模板成员函数分文件编写产生的问题以及解决方式
问题:
- 类模板中成员函数创建时机是在调用阶段,导致分文件编写是链接不到
解决:
- 解决方式1:直接包含.cpp源文件
- 解决方式2:将声明和实现写到同一个文件中,并更改后缀名为.hpp,hpp是约定的名称,并不是强制
示例:
person.hpp中代码
#include <iostream>
#include <string>
using namespace std;
// 类模板分文件编写问题和解决
#include "Person.hpp"
void testA()
{
Person<string, int> p("Tom", 20);
p.showPerson();
}
int main()
{
testA();
system("pause");
return 0;
}
main.cpp中代码
#include <iostream>
#include <string>
using namespace std;
// 类模板分文件编写问题和解决
#include "Person.hpp"
void testA()
{
Person<string, int> p("Tom", 20);
p.showPerson();
}
int main()
{
testA();
system("pause");
return 0;
}
类模板与友元
学习目标:
- 掌握类模板配合友元函数的类内和类外实现
全局函数类内实现 - 直接在类内声明友元即可
全局函数类外实现 - 需要提前让编译器知道全局函数存在
示例:
#include <iostream>
#include <string>
using namespace std;
// 通过全局函数 打印Person信息
// 提前让编译器知道全局函数存在
template<class T1, class T2>
class Person;
template<class T1, class T2>
void printPerson2(Person<T1, T2>& p);
template<class T1,class T2>
class Person
{
//全局函数 类内实现
friend void printPerson(Person<T1, T2>& p)
{
cout << "姓名:" << p.m_Name << "\t年龄:" << p.m_Age << endl;
}
//全局函数 类外实现
//加空模板参数列表
//如果全局函数是类外实现 需要提前让编译器知道全局函数存在
friend void printPerson2<>(Person<T1, T2>& p);
public:
Person(T1 name, T2 age)
{
this->m_Name = name;
this->m_Age = age;
}
private:
T1 m_Name;
T2 m_Age;
};
template<class T1, class T2>
void printPerson2(Person<T1, T2>& p)
{
cout << "内外实现---姓名:" << p.m_Name << "\t年龄:" << p.m_Age << endl;
}
void testA()
{
Person<string, int> p("Tom", 20);
printPerson(p);
printPerson2(p);
}
int main()
{
testA();
system("pause");
return 0;
}
类模板案例
案例描述:实现一个通用的数组类,要求如下:
- 可以对内置数据类型以及自定义数据类型的数据进行存储
- 将数组中的数据存储到堆区
- 构造函数中可以传入数组的容量
- 提供对应的拷贝构造函数以及operator=防止浅拷贝问题
- 提供尾差法和尾删法对数组中的数据进行增加和删除
- 可以通过下标的方式访问数组中的元素
- 可以获取数组宏当前元素个数和数组的容量
示例:
myArray.hpp中代码
#pragma once
#include <iostream>
using namespace std;
#include <string>
template<class T>
class MyArray
{
public:
// 有参构造
MyArray(int capacity)
{
//cout << "myarray的有参构造调用" << endl;
this->m_Capacity = capacity;
this->m_Size = 0;
this->pAddress = new T[this->m_Capacity];
}
//拷贝构造
MyArray(const MyArray& arr)
{
//cout << "myarray的拷贝构造调用" << endl;
this->m_Capacity = arr.m_Capacity;
this->m_Size = arr.m_Size;
//浅拷贝
//this->pAddress = arr.pAddress;
//深拷贝
this->pAddress = new T[arr.m_Capacity];
//将arr中的数据都拷贝过来
for (int i = 0; i < this->m_Size; i++)
{
this->pAddress[i] = arr.pAddress[i];
}
}
//operator= 防止浅拷贝问题
MyArray& operator=(const MyArray& arr)
{
//cout << "myarray的=构造调用" << endl;
//先判断原来堆区是否有数据,如果有先释放
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 = arr.pAddress;
//深拷贝
this->pAddress = new T[arr.m_Capacity];
//将arr中的数据都拷贝过来
for (int i = 0; i < this->m_Size; i++)
{
this->pAddress[i] = arr.pAddress[i];
}
return *this;
}
// 尾插法
void pushBack(const T& val)
{
//判断容量是否等于大小
if (this->m_Capacity == this->m_Size)
{
return;
}
this->pAddress[this->m_Size] = val;
this->m_Size++;
}
// 尾删法
void popBack()
{
// 让用户访问不到最后一个元素,即为尾删,逻辑删除
if (this->m_Size == 0)
{
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()
{
//cout << "myarray的析构构造调用" << endl;
if (this->pAddress != NULL)
{
delete[] this->pAddress;
this->pAddress = NULL;
}
}
private:
T* pAddress; //指针指向堆区开辟的真实数组
int m_Capacity; //数组容量
int m_Size; //数组大小
};
main.cpp中代码
#include <iostream>
#include <string>
using namespace std;
#include "MyArray.hpp"
template<class T>
void printArray(MyArray<T>& arr)
{
for (int i = 0; i < arr.getSize(); i++)
{
cout << arr[i] << endl;
}
}
void testA()
{
MyArray<int> arr1(5);
for (int i = 0; i < 5; i++)
{
arr1.pushBack(i);
}
cout << "arr1打印输出:" << endl;
printArray(arr1);
cout << "arr1的容量为:" << arr1.getCapacity() << endl;
cout << "arr1的大小为:" << arr1.getSize() << endl;
MyArray<int>arr2(arr1);
cout << "arr2打印输出:" << endl;
printArray(arr2);
//尾删
arr2.popBack();
cout << "arr2的容量为:" << arr2.getCapacity() << endl;
cout << "arr2的大小为:" << arr2.getSize() << endl;
cout << "arr2尾删后打印输出:" << endl;
printArray(arr2);
}
//测试自定义数据类型
class Person
{
public:
Person(string name,int age)
{
this->m_Age = age;
this->m_Name = name;
}
public:
string m_Name;
int m_Age;
Person() = default;
};
void printPersonArray(MyArray<Person>& arr)
{
for (int i = 0; i < arr.getSize(); i++)
{
cout << "姓名:" << arr[i].m_Name << "\t年龄:" << arr[i].m_Age << endl;
}
}
void testB()
{
MyArray<Person> arr(10);
Person p1("孙悟空", 999);
Person p2("韩信", 30);
Person p3("妲己", 20);
Person p4("赵云", 25);
Person p5("安其拉", 20);
arr.pushBack(p1);
arr.pushBack(p2);
arr.pushBack(p3);
arr.pushBack(p4);
arr.pushBack(p5);
printPersonArray(arr);
cout << "arr的容量为:" << arr.getCapacity() << endl;
cout << "arr的大小为:" << arr.getSize() << endl;
}
int main()
{
//testA();
testB();
system("pause");
return 0;
}