模板
1 模板概念
模板就是建立通用的磨具,大大提高复用性
模板特点:
(1)模板不可以直接使用,他只是一个框架
(2)模板的通用性不是万能的
2 函数模板
C++另一种编程思想为泛型编程,主要利用的技术就是模板。
C++提供两种模板机制:函数模板和类模板
2.1 函数模板语法
函数模板作用: 建立一种通用函数,其函数返回值类型和形参类型可以不具体制定,用一个虚拟的类型来代表。
函数模板语法:
template
函数声明或定义
1.template:声明创建模板
2.typename:表明其后面是一种数据类型,可以用class代替
3.T:通用的数据类型,名称可以替换,通常为大写字母
#include <iostream>
using namespace std;
//函数模板
template <typename T>//声明一个模板,告诉编译器后面代码中紧跟着的T不要报错,T是一个通用数据类型
void mySwap(T& a, T& b)//函数模板,实现两个数据互换
{
T temp = a;
a = b;
b = temp;
}
void test01()
{
int a = 10;
int b = 20;
//利用函数模板交换:
//(1)自动类型推导
mySwap(a, b);//自动推导T是a,b类型
cout << "a=" << a << endl;
cout << "b=" << b << endl;
//(2)显示指定类型
int c = 10;
int d = 20;
mySwap<int>(c, d);
cout << "c=" << c<< endl;
cout << "d=" << d << endl;
}
int main()
{
test01();
}
总结:
(1)函数模板利用关键字template
(2)使用函数模板有两种方式:自动类型推导、显示指定类型
(3)模板的目的是为了提高复用性,将类型参数化
2.2 函数模板注意事项
注意事项:
(1)自动类型推导,必须推导出一致的数据类型T,才可以使用
(2)模板必须要确定出T的数据类型,才可以使用
#include <iostream>
using namespace std;
//函数模板注意事项
//1.自动类型推导,必须推导出一致的数据类型T才可以使用
template <typename T>//声明一个模板,告诉编译器后面代码中紧跟着的T不要报错,T是一个通用数据类型。typename可以替换为class
void mySwap(T& a, T& b)//函数模板,实现两个数据互换
{
T temp = a;
a = b;
b = temp;
}
void test01()
{
int a = 10;
int b = 20;
char c = 'c';
mySwap(a, b);//正确:自动推导T,a,b类型一致
//mySwap(a, c);//错误:必须推导出一致的数据类型T才可以使用,本例中T类型不一致
}
//2.模板必须要确定出T的数据类型,才可以使用
template <typename T>
void func()
{
cout << "func调用" << endl;
}
void test02()
{
//func();//错误,T必须推导出数据类型。
func<int>();//显示指定T的数据类型。
}
int main()
{
test01();
}
2.3 函数模板案例
案例描述:
利用函数模板封装一个排序的函数,可以对不同数据类型数组进行排序
排序规则从大到小,排序算法为选择排序
分别利用char数组和int数组进行测试
#include <iostream>
using namespace std;
//实现通用 对数组进行排序:
//规则从大到小
//算法 选择排序
//(1)交换函数模板
template <typename T>
void mySwap(T& a, T& b)
{
T temp = a;
a = b;
b = temp;
}
//(2)排序函数模板
template <typename 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[j] > arr[max])
{
max = j;//更新最大值下标
}
}
if (max != i)
{
//交换值
mySwap(arr[max], arr[i]);
}
}
}
//(3)打印数组模板
template <typename T>
void printArray(T arr[],int len)
{
for (int i = 0; i < len; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
void test01()
{
char charArr[] = "bsikcac";//创建字符数组
int num = sizeof(charArr) / sizeof(char);
mySort(charArr, num);
printArray(charArr, num);
}
void test02()
{
int intArray[] = { 8,8,9,2,7,1,8,2,6,5 };
int num = sizeof(intArray) / sizeof(int);
mySort(intArray, num);
printArray(intArray, num);
}
int main()
{
test01();//测试char数组排序
test02();//测试int数组排序
}
2.4 普通函数和函数模板的区别
区别:
(1)普通函数调用时,可以发生自动类型转换(隐式类型转换)
(2)函数模板调用时,如果利用自动类型推导,不会发生隐式类型转换
(3)函数模板调用时,如果利用指定类型的方式,可以发生隐式类型转换
#include <iostream>
using namespace std;
//普通函数和函数模板的区别
//1.普通函数是发生隐式类型转换的
//2.函数模板在自动推导类型调用时,是不发生隐式类型转换的
//3.函数模板在指定属性方式调用时,发生隐式类型转换
//(1)普通函数:可以发生隐式类型转换
int ADD01(int a, int b)
{
return a + b;
}
void test01()
{
int a = 10;
int b = 20;
char c = 'c';
cout << ADD01(a, b) << endl;//无隐式类型转换
cout << ADD01(a, c) << endl;//发生隐式类型转换
}
//(2)函数模板:自动类型推导不能发生自动类型转换,指定类型时可以发生自动类型转换
template <typename T>
T ADD02(T a, T b)
{
return a + b;
}
void test02()
{
int a = 10;
int b = 20;
char c = 'c';
//cout << ADD02(a, c) << endl;//自动类型推导:无隐式类型转换,报错
cout << ADD02<int>(a, c) << endl;//指定类型:发生隐式类型转换
}
int main()
{
test01();
test02();
}
**总结:**建议使用显示指定类型的方式,调用函数模板,因为可以自己确定通用类型T
2.5 普通函数与函数模板的调用规则
普通函数与函数模板的调用规则:
(1)如果函数模板和普通函数都可以实现,优先调用普通函数
(2)可以通过空模板参数列表,强制调用函数模板
(3)函数模板也可以发生重载
(4)如果函数模板可以产生更好的匹配,优先调用函数模板
#include <iostream>
using namespace std;
// 普通函数与函数模板的调用规则:
// (1)如果函数模板和普通函数都可以实现,优先调用普通函数
//(2)可以通过空模板参数列表来强制调用函数模板
//(3)函数模板也可以发生重载
// (4)如果函数模板可以产生更好的匹配,优先调用函数模板
void myPrint(int a,int b)
{
cout << "调用普通函数" << endl;
}
template <typename T>
void myPrint(T a, T b)
{
cout << "调用函数模板" << endl;
}
template <typename T>
void myPrint(T a, T b,, T c)
{
cout << "调用重载的函数模板" << endl;
}
void test01()
{
int a = 10;
int b = 20;
cout << "1.优先调用普通函数" << endl;
myPrint(a,b);//
cout << "2.通过空模板参数,强制调用模板函数" << endl;
myPrint<>(a, b);//
cout << "3.函数模板也可以发生重载" << endl;
myPrint(a, b, 100);//
cout << "4.如果函数模板可以产生更好的匹配,优先调用函数模板" << endl;
char c1 = 'a';
char c2 = 'b';
myPrint(c1,c2);//
}
int main()
{
test01();
}
总结:既然提供了函数模板,最好就不要提供普通函数,否者容易出现二义性。
2.6 模板的局限性
局限性:模板的通用性并不是万能的
例:
//如果传入的数组是a,b是一个数组,就无法实现
template <typename T>
void myPrint(T a, T b)
{
a = b;
}
//如果传入的是像Person一样的自定义数据类型,也无法实现
template <typename T>
void myPrint(T a, T b)
{
if (a > b)
{
cout << "a>b" << endl;
}
}
为了解决上述局限性,提供模板的重载,可以为这些特定的类型提供具体化的模板。
#include <iostream>
using namespace std;
#include<string>
//模板的局限性
//模板并不是万能的,有些特定数据类型,需要用具体化方式做特殊实现
class Person
{
public:
Person(string name,int age)
{
this->m_Name = name;
this->m_Age = age;
}
//姓名
string m_Name;
//年龄
int m_Age;
};
//1.对比两个数据是否相等的函数(普通数据类型)
template <typename T>
bool compare(T &a, T &b)
{
if (a == b)
{
return true;
}
else
{
return false;
}
}
//2.对比两个数据是否相等的函数(Person类的数据)
template<> bool compare(Person& p1 , Person& p2)
{
if (p1.m_Name == p2.m_Name && p1.m_Age==p2.m_Age)
{
return true;
}
else
{
return false;
}
}
void test01()
{
int a = 10;
int b = 20;
bool ret = compare(a,b);
if (ret)
{
cout << "a==b" << endl;
}
else
{
cout << "a!=b" << endl;
}
}
void test02()
{
Person p1("Tom", 10);
Person p2("Tom", 10);
bool ret = compare(p1, p2);//出错,因为无法比较a是否==b
if (ret)
{
cout << "p1==p2" << endl;
}
else
{
cout << "p1!=p2" << endl;
}
}
int main()
{
test01();
test02();
}
总结:
(1)利用具体化的模板,可以解决自动以类型的通用化
(2)学习模板并不是为了写模板,而是在STL能够运用系统提供的模板
3 类模板
3.1 类模板语法
类模板作用:
建立一个通用类,类中的成员 数据类型可以不具体指定,用一个虚拟的类型来代表。
语法:
template
类
template:声明创建模板
typename:表明其后面的符号是一种数据类型,可以用class代替
T:通用数据类型,名称可以替换,通常为大写字母
#include<iostream>
using namespace std;
#include <string>
//类模板
template <class NameType,class AgeType>
class Person
{
public:
Person(NameType name,AgeType age)
{
this->m_Name = name;
this->m_Age = age;
}
void showPerson()
{
cout << "name:" << this->m_Name << "年龄:" << this->m_Age << endl;
}
NameType m_Name;
AgeType m_Age;
};
void test01()
{
Person <string, int> p1("孙悟空", 999);
p1.showPerson();
}
int main()
{
test01();
}
总结:类模板和函数模板语法相似,在声明模板template后面加类,此类称为类模板。
3.2 类模板和函数模板的区别
类模板和函数模板区别主要有两点:
(1)类模板没有自动类型推导的使用方式(只有显示指定类型的方式)
(2)类模板在模板参数列表中可以有默认参数:例template <class NameType, class AgeType=int>
#include<iostream>
using namespace std;
#include <string>
//类模板与函数模板去表
template <class NameType, class AgeType=int>
class Person
{
public:
Person(NameType name, AgeType age)
{
this->m_Name = name;
this->m_Age = age;
}
void showPerson()
{
cout << "name:" << this->m_Name << "年龄:" << this->m_Age << endl;
}
NameType m_Name;
AgeType m_Age;
};
//1.类模板没有自动类型推导的使用方式,只能显示指定类型
void test01()
{
//错误方式:无法使用自动类型推导
//Person p1("孙悟空", 999);
Person <string, int> p1("孙悟空", 999);
p1.showPerson();
}
//2.类模板在模板参数列表中可以有默认参数
void test02()
{
//类模板中template <class NameType, class AgeType=int>有默认类型参数,所以在显示指定类型的时候,可以省略该参数
Person <string> p2("猪八戒", 999);
p2.showPerson();
}
int main()
{
test01();
test02();
}
3.3 类模板中成员函数创建时机
类模板中成员函数和普通类中成员函数创建时机是有区别的:
(1)普通类中的成员函数—开始就创建。
(2)类模板中的成员函数在调用时才创建。
#include<iostream>
using namespace std;
#include <string>
//类模板中成员函数创建时机
//类模板中成员函数在调用时才去创建
class Person1
{
public:
void showPerson1()
{
cout << "Person1 show" << endl;
}
};
class Person2
{
void showPerson2()
{
cout << "Person2 show" << endl;
}
};
template <class T>
class MyClass
{
public:
T obj;
//类模板中的成员函数
void func1()
{
obj.showPerson1();
}
void func2()
{
obj.showPerson2();
}
};
void test01()
{
MyClass <Person1> p1 ;
p1.func1();
}
int main()
{
test01();
}
总结:
类模板中的成员函数并不是一开始就创建的,在调用时才会去创建
3.4 类模板对象做函数参数
学习目标:
类模板实例化出的对象,像函数传参的方式
三种传入方式:
(1)指定传入类型,直接显示对象的数据类型(使用广泛)
(2)参数模板化,将对象中的参数变为模板进行传递
(3)整个类模板化,将这个对象类型 模板化进行传递
#include<iostream>
using namespace std;
#include <string>
//类模板对象做函数参数
template <class T1,class T2>
class Person
{
public:
Person (T1 name, T2 age)
{
this->m_Name = name;
this->m_Age = age;
}
void showPerson()
{
cout << "姓名:" << this->m_Name << "年龄:" << this->m_Age << endl;
}
T1 m_Name;
T2 m_Age;
};
//1.指定传入类型
void printPerson1(Person <string, int> &p)
{
p.showPerson();
}
void test01()
{
Person <string, int> p1("孙悟空", 999);
printPerson1(p1);
}
//2.参数模板化
template <class T1, class T2>
void printPerson2(Person <T1,T2> & p)
{
p.showPerson();
}
void test02()
{
Person <string, int> p1("猪八戒", 998);
printPerson2(p1);
}
//3.整个类模板化
template <class T>
void printPerson3(T & p)
{
p.showPerson();
}
void test03()
{
Person <string, int> p1("唐僧", 1000);
printPerson3(p1);
}
int main()
{
test01();
test02();
test03();
}
3.5 类模板与继承
当类模板碰到继承时,需要注意到以下几点:
(1)当子类继承的父类是一个类模板时,子类在声明的时候,要指定出父类中T的类型,若不指定编译器将无法给子类分配内存。
(2)如果想灵活指定出父类中T的类型,子类也需要变为类模板。
#include<iostream>
using namespace std;
#include <string>
//类模板与继承
template <class T >
class Base
{
public:
T m ;
};
//(1)class Son :public Base//错误:必须知道父类中的T类型,才能继承给子类
class Son :public Base<int>
{
};
void test01()
{
Son s1;
}
//(2)如果想灵活指定父类中T类型,子类需要变为类模板
template <class T1,class T2 >
class Son1 :public Base<T2>
{
public:
Son1()
{
cout << "T1的类型为:" << typeid(T1).name() << endl;
cout << "T2的类型为:" << typeid(T2).name() << endl;
}
T1 obj;
};
void test02()
{
Son1<int,char> s2;
}
int main()
{
test01();
test02();
}
总结:如果父类是类模板,子类在继承时需要指定出父类中T的数据类型
3.6 类模板成员函数类外实现
学习目标:能够掌握类模板中的成员函数类外实现
#include<iostream>
using namespace std;
#include <string>
//类模板 成员函数类外实现
template <class T1,class T2>
class Person
{
public:
Person(T1 name, T2 age);//成员函数声明
void showPerson();//成员函数声明
T1 m_Name;
T2 m_Age;
};
//成员函数类外实现
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 << "姓名:" << this->m_Name << " 年龄:" << this->m_Age << endl;
}
void test01()
{
Person<string, int>p("TOM", 20);
p.showPerson();
}
int main()
{
test01();
}
3.7 类模板分文件编写
学习目标:掌握类模板成员函数分文件编写产生的问题以及解决方式
问题:类模板中成员函数创建时机是在调用阶段,导致分文件编写时链接不到
解决:
(1)直接包含.cpp源文件
(2)将声明和实现写到同一个文件中,并更改后缀名为.hpp,hpp是约定的名称,并不是强制。
1.创建person.h文件
#pragma once
#include <iostream>
using namespace std;
#include <string>
template <class T1,class T2>
class Person
{
public:
Person(T1 name, T2 age);
void showPerson();
T1 m_Name;
T2 m_Age;
};
2.创建person.cpp文件:该文件包含person.h
#include <iostream>
using namespace std;
#include <string>
#include "person.h"//包含头文件
template <class T1,class T2>
Person<T1, T2>::Person(T1 name, T2 age)
{
m_Name = name;
m_Age = age;
}
template <class T1, class T2>
void Person<T1, T2>::showPerson()
{
cout << "姓名:" << this->m_Name << " 年龄:" << this->m_Age << endl;
}
3.类模板分文件编写.cpp文件
错误示范:#include “person.h”//包含头文件
#include <iostream>
using namespace std;
#include <string>
#include "person.h"//包含头文件
template <class T1,class T2>
Person<T1, T2>::Person(T1 name, T2 age)
{
m_Name = name;
m_Age = age;
}
template <class T1, class T2>
void Person<T1, T2>::showPerson()
{
cout << "姓名:" << this->m_Name << " 年龄:" << this->m_Age << endl;
}
解决方法1:直接包含.cpp源文件
#include <iostream>
using namespace std;
#include <string>
//解决方法1:直接包含.cpp原文件(正常都是包含.h头文件)
#include "person.cpp";
void test01()
{
Person<string,int> p1("TOM", 18);
p1.showPerson();
}
int main()
{
test01();
}
解决方法2:将.h和.cpp源文件中的内容写到一起,将后缀名改为.hpp文件
#pragma once
#include <iostream>
using namespace std;
#include <string>
template <class T1, class T2>
class Person
{
public:
Person(T1 name, T2 age);
void showPerson();
T1 m_Name;
T2 m_Age;
};
template <class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age)
{
m_Name = name;
m_Age = age;
}
template <class T1, class T2>
void Person<T1, T2>::showPerson()
{
cout << "姓名:" << this->m_Name << " 年龄:" << this->m_Age << endl;
}
使用时直接包含hpp文件
3.8 类模板与友元
学习目标:掌握类模板配合友元函数的类内和类外实现
全局函数类内实现——直接在类内声明友元即可
全局函数类外实现——需要提前让编译器知道全局函数的存在
#include<iostream>
using namespace std;
#include <string>
//让编译器知道全局函数的存在
template <typename T1, typename T2>
class Person;
template <typename T1, typename T2>
void printPerson2(Person<T1, T2> p)
{
cout << "姓名:" << p.m_Name << "年龄:" << p.m_Age << endl;
}
template <typename T1,typename T2>
class Person
{
//全局函数,类内实现(声明为友元)
friend void printPerson(Person<T1,T2> p)
{
cout << "姓名:" << p.m_Name << "年龄:" << 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;
};
//1.全局函数在类内实现的测试案例
void test01()
{
Person<string, int> p("jarry", 20);
printPerson(p);
}
//2.全局函数在类外实现的测试案例
void test02()
{
Person<string, int> p1("tom", 20);
printPerson2(p1);
}
int main()
{
test01();
test02();
}
3.9 类模板案例
案例描述:实现一个通用的数组类,要求如下
(1)可以对内置数据类型以及自定义数据类型的数据进行存储
(2)将数组中的数据开辟到堆区
(3)构造函数中可以传入数组的容量
(4)提供对应的拷贝构造函数以及operator=防止浅拷贝问题
(5)提供尾插法和尾删法对数组中的数据进行增加和删除
(6)可以通过下标的方式访问数组中的元素
(7)可以获取数组中当前元素个数和数组容量
步骤1:创建MyArray.hpp文件
#pragma once
#include <iostream>
using namespace std;
#include <string>
//自己通用的数组类
template <typename T>
class MyArray
{
private:
//数组的地址:指针指向堆区开辟的真实数组
T* pAddress;//
//数组容量
int m_Capacity;
//数组大小:设置数组当前包含的数据的数量
int m_Size;
public:
//构造函数:设置容量、大小
MyArray(int capacity)
{
this->m_Capacity = capacity;//数组容量
this->m_Size = 0;
this->pAddress = new T[this->m_Capacity];//根据数组的容量开辟数组空间,返回指向数组的指针(地址)
}
//析构函数
~MyArray()
{
if (this->pAddress != NULL)
{
delete[] this->pAddress;
this->pAddress = NULL;
}
}
//拷贝构造函数:防止浅拷贝
MyArray(const MyArray& arr)
{
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)
{
//先判断原来堆区是否有数据,如果有先释放
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];
//将arr中的数据都拷贝过来
for (int i = 0; i < this->m_Size; i++)
{
this->pAddress[i] = arr.pAddress[i];
}
return *this;
}
};
步骤2:类模板案例.cpp
#include<iostream>
using namespace std;
#include <string>
#include "MyArray.hpp"//包含hpp文件
void test01()
{
cout << "普通创建对象:调用构造函数" << endl;
MyArray<int> arr(5);
cout << "通过对象创建对象:调用拷贝函数" << endl;
MyArray<int> arr1(arr);
cout << "重载operator=调用:" << endl;
MyArray<int> arr2(100);//重载operator=调用
arr2 = arr1;
}
int main()
{
test01();
}
步骤3:MyArray.hpp新增代码
在数组中插入数据——MyArray.hpp中添加函数void Push_Back()
//尾插法:插入数据
void Push_Back(const T &d)
{
//先判断容量是否符合
if (this->m_Capacity == this->m_Size)
{
cout << "容量达上限,不能插入数据" << endl;
return;
}
this->pAddress[this->m_Size] = d;
this->m_Size ++;
}
数组中删除数据——在MyArray.hpp中添加函数void Pop_Back()
//尾删法:删除数据
void Pop_Back( )
{
//先判断容量是否符合
if ( this->m_Size==0)
{
cout << "没有数据可以删除" << endl;
return;
}
this->m_Size--;//逻辑上删除,使其不能访问该数据
}
重载[]通过下标方式访问数组数据
//重载[]:通过下标方式访问数组数据
T& operator[](int index)
{
return this->pAddress[index];
}
返回数组容量和大小
//返回数组容量
int get_capacity()
{
return this->m_Capacity;
}
//返回数组大小
int get_size()
{
return this->m_Size;
}
步骤4:完整测试代码,编写类模板案例.cpp
#include<iostream>
using namespace std;
#include <string>
#include "MyArray.hpp"//包含hpp文件
void test01()
{
cout << "普通创建对象:调用构造函数" << endl;
MyArray<int> arr(5);
cout << "通过对象创建对象:调用拷贝函数" << endl;
MyArray<int> arr1(arr);
cout << "重载operator=调用:" << endl;
MyArray<int> arr2(100);//重载operator=调用
arr2 = arr1;
}
void printIntArray(MyArray<int> &arr)
{
for (int i = 0; i < arr.get_size(); i++)
{
cout << arr[i] <<" ";//因为重载了[]因此可以通过下标访问
}
cout << endl;
}
void test02()
{
MyArray<int> arr(5);
//(1)测试尾插法:向数组中插入数据
for (int i = 0; i < 5; i++)
{
arr.Push_Back(i);
}
//(2)测试重载[]利用下标输出数据
cout << "arr的打印输出为:" << endl;
printIntArray(arr);
//(3)测试打印数组的容量及大小
cout << "arr的容量为:" << arr.get_capacity() << endl;
cout << "arr的大小为:" << arr.get_size() << endl;
//(4)测试尾删法删除数据
MyArray<int> arr1(arr);
arr1.Pop_Back();
printIntArray(arr);
printIntArray(arr1);
}
int main()
{
test01();
test02();
}