【C++ 泛型编程01:模板】函数模板与类模板

【模板】

  • 除了OOP外,C++另一种编程思想称为 泛型编程 ,主要利用的技术就是模板

  • C++提供两种模板机制:函数模板类模板

函数模板

函数模板作用

建立一个通用函数,其函数返回值类型和形参类型可以不具体制定,用一个虚拟的类型来代表。

语法

template
函数声明或定义

解释

template --- 声明创建模板

typename --- 表面其后面的符号是一种数据类型,可以用class代替

T --- 通用的数据类型,名称可以替换,通常为大写字母

例子

举个例子,我们要写一些交换数据的函数

#include
using namespace std;

//两个整形交换的函数
void swapInt(int& a, int& b) {
	int temp = a;
	a = b;
	b = temp;
}

//交换浮点型函数
void swapDouble(double& a, double& b) {
	double temp = a;
	a = b;
	b = temp;
}

void test01() {
	int a = 10;
	int b = 20;

	swapInt(a, b);

	cout 

很简单,但是像上面那样写函数,那交换不同的数据交换就要有对应的函数,很冗余

如果可以先不告诉函数输入参数的类型,用的时候再确定,就可以抽象一个通用的交换函数

这就是模板的用途,于是上面的例子便可以写成:

#include
using namespace std;

//函数模板
template //声明一个模板,后面代码里面用T的时候不要报错,T为通用数据类型
void MySawp(T& a, T& b) {
	T temp = a;
	a = b;
	b = temp;
}

void test01() {
	int a = 10;
	int b = 20;

	//模板有两种使用方式
	//1、自动类型推导数据类型
	//MySawp(a, b);

	//2、显式指定数据类型
	MySawp(a, b);
	cout 

总结

  • 函数模板利用关键字 template
  • 使用函数模板有两种方式:自动类型推导、显示指定类型
  • 模板的目的是为了提高复用性,将类型参数化

注意事项

  • 自动类型推导,必须推导出一致的数据类型T,才可以使用

  • 模板必须要确定出T的数据类型,才可以使用

例子
#include
using namespace std;

template //typename可以替换为class
void MySawp(T& a, T& b) {
	T temp = a;
	a = b;
	b = temp;
}

//1、自动类型推导,必须推导出一致的数据类型T,才可以使用
void test01() {
	int a = 10;
	int b = 20;
	char c = 'c';

	//利用函数模板交换
	//两种方式
	//1、自动类型推导
	MySawp(a, b);//对
	//MySawp(a, c);//错,推导不出一致的T类型

	cout 
void func()//func写在template声明后面就已经是一个函数模板了
{//不管模板里面用没用T,都必须给T一个数据类型,func才可以被调用
	cout (); //利用显示指定类型的方式,给T一个类型,才可以使用该模板
}

int main() {
	test01();

	system("pause");
	return 0;
}

实例:排序函数封装

案例描述

  • 利用函数模板封装一个排序的函数,可以对不同数据类型数组进行排序
  • 排序规则从大到小,排序算法为选择排序
  • 分别利用char数组int数组进行测试

代码

#include
#include
using namespace std;


//交换的函数模板
template
void mySwap(T& a, T& b)
{
	T temp = a;
	a = b;
	b = temp;
}


////1、先写一个选择排序的函数
//void sort(int num[],int len) {
//	
//	for (int i = 0; i  num[max]) {
//				max = j;
//			}
//		}
//		//max不等于i,出现新的max值
//		//更新最大值
//		if (max != i) {
//			mySwap(num[max], num[i]);
//		}
//
//	}
//}

template // 也可以替换成typename
//利用选择排序,进行对数组从大到小的排序
void mySort(T arr[], int len)
{
	for (int i = 0; i 
void bubleSort(T arr[], int len) {
	T temp;
	for (int i = 0; i  arr[j + 1]) {
				temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
}

//打印
template
void printArray(T arr[], int len) {

	for (int i = 0; i 

区别

普通函数与函数模板区别:

  • 普通函数调用时可以发生自动类型转换(隐式类型转换)
  • 函数模板调用时,如果利用自动类型推导,不会发生隐式类型转换
  • 如果利用显示指定类型的方式,可以发生隐式类型转换

建议使用显示指定类型的方式,调用函数模板,因为可以自己确定通用类型T

类模板

类模板作用

建立一个通用类,类中的成员 数据类型可以不具体制定,用一个虚拟的类型来代表。

语法

template
类

解释

template --- 声明创建模板

typename --- 表面其后面的符号是一种数据类型,可以用class代替

T --- 通用的数据类型,名称可以替换,通常为大写字母

例子

#include
using namespace std;
#include 

//给出类中成员属性的通用数据类型,可以直接给个默认值,后面就不用再写了
//Person为类模板,有NameType、AgeType两个通用数据类型
template
class Person
{
public:
	Person(NameType name, AgeType age)
	{
		this->mName = name;
		this->mAge = age;
	}
	void showPerson()
	{
		cout mName mAge P1("jk", 999);
	P1.showPerson();
}

//类模板没有自动类型推导,必须指定数据类型
void test02()
{
	// 指定NameType 为string类型,AgeType 为 int类型
	Person P1("dk", 9);
	P1.showPerson();
}

int main() {
	test01();

	system("pause");
	return 0;
}

类模板与函数模板区别

类模板与函数模板区别主要有两点:

  1. 类模板没有自动类型推导的使用方式
  2. 类模板在模板参数列表中可以有默认参数

总结

类模板和函数模板语法相似,在声明模板template后面加类,此类称为类模板

类模板对象做函数参数

类模板实例化出的对象,作为参数传向函数时,一共有三种传入方式:

  1. 指定传入的类型 --- 直接显示对象的数据类型
  2. 参数模板化 --- 将对象中的参数变为模板进行传递
  3. 整个类模板化 --- 将这个对象类型 模板化进行传递

指定传入的类型

#include
using namespace std;
#include 
#include 

//类模板
template
class Person
{
public:
	Person(NameType name, AgeType age)
	{
		this->mName = name;
		this->mAge = age;
	}
	void showPerson()
	{
		cout mName mAge & p)
{
	p.showPerson();
}
void test01()
{
	Person p("jk", 100);
	printPerson1(p);
}

int main() {
	test01();
    
	system("pause");
	return 0;
}

参数模板化

#include
using namespace std;
#include 
#include 

//类模板
template
class Person
{
public:
	Person(NameType name, AgeType age)
	{
		this->mName = name;
		this->mAge = age;
	}
	void showPerson()
	{
		cout mName mAge 
void printPerson2(Person& p)
{
	p.showPerson();
	cout p("nnd", 90);
	printPerson2(p);
}

int main() {
	test02();

	system("pause");
	return 0;
}

整个类模板化

#include
using namespace std;
#include 
#include 

//类模板
template
class Person
{
public:
	Person(NameType name, AgeType age)
	{
		this->mName = name;
		this->mAge = age;
	}
	void showPerson()
	{
		cout mName mAge 
void printPerson3(T& p)
{
	cout p("sb", 30);
	printPerson3(p);
}

int main() {

	test03();

	system("pause");
	return 0;
}
  • 通过类模板创建的对象,可以有三种方式向函数中进行传参
  • 使用比较广泛是第一种:指定传入的类型

类模板与继承

当类模板碰到继承时,需要注意一下几点:

  • 当子类继承的父类是一个类模板时,子类在声明的时候,要指定出父类中T的类型
  • 如果不指定,编译器无法给子类分配内存
  • 如果想灵活指定出父类中T的类型,子类也需变为类模板

例子

#include
using namespace std;
#include 

template
class Base{
	T m;
};

//class Son:public Base  //错误,c++编译需要给子类分配内存,必须知道父类中T的类型才可以向下继承
//简单来说,继承需要用到父类Base,Base是个类模板,那就必须指定Base中的通用数据类型
class Son :public Base{ //必须指定一个类型
};

void test01(){
	Son c;
}

//类模板继承类模板 ,可以用T2指定父类中的T类型
template
class Son2 :public Base{
public:
	Son2(){
		cout  child1;
}

int main() {
	test01();
	test02();

	system("pause");
	return 0;
}

如果父类是类模板,子类需要指定出父类中T的数据类型

类模板分文件编写(以及类外实现)

单个文件的写法

例子,直接在单个文件中编写代码

#pragma once
#include
using namespace std;
#include 

template
class Person {
public:
	Person(T1 name, T2 age){
	this->m_Name = name;
	this->m_Age = age;
	}

	void showPerson(){
	cout m_Name m_Age p1("jk", 18);
	p1.showPerson();

}

int main() {
	test01();

	system("pause");
	return 0;
}
类模板类外实现成员函数
#pragma once
#include
using namespace std;
#include 

template
class Person {
public:
	Person(T1 name, T2 age);

	void showPerson();

	T1 m_Name;
	T2 m_Age;
};

//类外实现
template
Person::Person(T1 name, T2 age){
	this->m_Name = name;
	this->m_Age = age;
}

template
void Person::showPerson() {
	cout m_Name m_Age p1("jk", 18);
	p1.showPerson();

}

int main() {
	test01();

	system("pause");
	return 0;
}

注意:加在类外实现的数据类型后面的初始化列表,里面不要再写class

问题

类模板中成员函数创建时机是在调用阶段,导致分文件编写时链接不到

分文件的写法

  • 解决方式1:直接包含.cpp源文件
  • 解决方式2:将声明和实现写到同一个文件中,并更改后缀名为.hpp,hpp是约定的名称,并不是强制
直接包含.cpp源文件

第一种解决方式是直接包含.cpp文件,这要直接include整个.cpp文件

错误写法

按照以前的分文件编写思路:

.h文件中要写函数、类的声明

.cpp文件通过include获取声明并实现对应函数

例如,

person.h

#pragma once
#include
using namespace std;
#include 

//声明类模板
template
class Person {
public:
	Person(T1 name, T2 age);

	void showPerson();

	T1 m_Name;
	T2 m_Age;
};

person.cpp

#include "person.h"

//类外实现
template
Person::Person(T1 name, T2 age) {
	this->m_Name = name;
	this->m_Age = age;
}

template
void Person::showPerson() {
	cout m_Name m_Age 

主函数

#pragma once
#include
using namespace std;
#include 
//第一种解决方式:直接包含.cpp文件
#include "person.cpp"

void test01() {
	Personp1("jk", 18);
	p1.showPerson();
}

int main() {
	test01();

	system("pause");
	return 0;
}

像上面这样分文件编写模板就会遇到问题(不涉及模板就是正确的),原因如下:

如果包含的是.h,那么编译器就只知道person.h中声明的成员函数,而没有person.cpp中的实现,肯定报错,链接不上

正确写法

既然导致错误的原因是编译器没有读到person.cpp中对应的函数实现,那直接让它读到不就完了

因此,一种简单粗暴的方法是:将函数的声明和实现都写在一块,然后在写有主函数的文件中通过include导入

实际上就是将单一文件编写的程序拆分了一下又合起来

person.cpp

#pragma once
#include
using namespace std;
#include 

template
class Person {
public:
	Person(T1 name, T2 age){
	this->m_Name = name;
	this->m_Age = age;
	}

	void showPerson(){
	cout m_Name m_Age 

主函数

#pragma once
#include
using namespace std;
#include 
//第一种解决方式:直接包含.cpp文件
#include "person.cpp"

void test01() {
	Personp1("jk", 18);
	p1.showPerson();

}

int main() {
	test01();

	system("pause");
	return 0;
}

显然,这种写法不够优雅

使用.hpp作为类模板的存放文件

这时候有小可爱就想了,那我把声明和实现都写在.h里面不就优雅了吗?

什么你觉得还不够优雅?那把这样的.h文件改名叫.hpp,以后大家都这样写类模板,够优雅了吧?

(ps:脱裤子放屁)

于是便有了下面的写法,这也是涉及类模板时,常用的分文件编写方式

person.hpp

#include 

template
class Person {
public:
	Person(T1 name, T2 age);

	void showPerson();

	T1 m_Name;
	T2 m_Age;
};

//类外实现
template
Person::Person(T1 name, T2 age) {
	this->m_Name = name;
	this->m_Age = age;
}

template
void Person::showPerson() {
	cout m_Name m_Age 

主函数

通过include导入这些实现

#pragma once
#include
using namespace std;
#include 
//第二种解决方式:将.h和.cpp中内容写到一起,后缀改为.hpp
#include "person.hpp"

void test01() {
	Personp1("jk", 18);
	p1.showPerson();
}

int main() {
	test01();
    
	system("pause");
	return 0;
}

类模板与友元

全局函数类内实现 - 直接在类内声明友元即可

全局函数类外实现 - 需要提前让编译器知道全局函数的存在

全局函数类内实现

#pragma once
#include
using namespace std;
#include 

template
class Person {
	//全局函数,类内实现
	friend void printPerson(Person &p) {
		cout m_Name = name;
		this->m_Age = age;
	}

private:
	T1 m_Name;
	T2 m_Age;
};

void test01() {
	Personp1("jk", 18);
	printPerson(p1);

}

int main() {
	test01();

	system("pause");
	return 0;
}

全局函数类外实现

#pragma once
#include
using namespace std;
#include 

//2、全局函数配合友元  类外实现 - 先做函数模板声明,下方在做函数模板定义,再做友元
template class Person;

//如果声明了函数模板,可以将实现写到后面,否则需要将实现体写到类的前面让编译器提前看到
//template void printPerson2(Person & p); 

template
void printPerson2(Person& p)
{
	cout 
class Person {
	//全局函数,类外实现
	// friend void printPerson2(Person& p);//记得加“”
	// 如果类外实现,需要让编译器提前知道该函数的存在
	friend void printPerson2(Person& p);

public:
	Person(T1 name,T2 age){
		this->m_Name = name;
		this->m_Age = age;
	}

private:
	T1 m_Name;
	T2 m_Age;
};

////还不能写在这里,必须写在开头让编译器先看见,要不然报错
//template
//void printPerson2(Person& p) {
//	cout p2("dk", 16);
	printPerson2(p2);
}

int main() {

	test02();

	system("pause");
	return 0;
}

总结

这里又一次体现了C++作者对于套娃和"万能编译器"的喜爱

忘了傻逼的全局函数类外实现吧(仅限涉及模板时)

就老老实实用全局函数做类内实现就好

类模板案例:实现通用的数组类

案例描述

实现一个通用的数组类,要求如下:

  • 可以对内置数据类型以及自定义数据类型的数据进行存储
  • 将数组中的数据存储到堆区
  • 构造函数中可以传入数组的容量
  • 提供对应的拷贝构造函数以及operator=防止浅拷贝问题
  • 提供尾插法和尾删法对数组中的数据进行增加和删除
  • 可以通过下标的方式访问数组中的元素
  • 可以获取数组中当前元素个数和数组的容量

实现模式

分文件写法:.hpp+.cpp主函数

那么主要的工作应该都在.hpp中完成,具体功能则在.cpp的主函数中测试

代码

myArray.hpp

先编写整体架构,提供有参构造函数和析构函数

有参构造函数和析构函数
//自定义通用数组类
#pragma once
#include
using namespace std;
#include 

//定义类模板MyArry
template
class MyArry {

public:
	//有参构造,传入容量
	MyArry(int capacity) {
		//cout m_Capacity = capacity;
		this->m_Size = 0;
		this->pAddress = new T[this->m_Capacity];
	}

	//涉及在堆中开辟空间,要写一下析构函数
	//释放内存
	~MyArry() {
		//cout pAddress != NULL) {
			delete[] this->pAddress;
			this->pAddress = NULL;//防止野指针
		}
	}

private:
	T* pAddress;//指针指向堆区开辟的真实数组

	int m_Capacity;//数组容量
	int m_Size;//数组大小
};
拷贝构造函数和重载运算符

接下来逐步添加功能,上述代码已经实现了:

  • 将数组中的数据存储到堆区
  • 构造函数中可以传入数组的容量

接下来要实现:对内置数据类型以及自定义数据类型的数据进行存储

这里要考虑浅拷贝问题,因此可以与第四点(拷贝构造)一块实现

关于浅拷贝问题,可以看看这篇,后续我计划再用一篇博客讨论讨论

言归正传

//自定义通用数组类
#pragma once
#include
using namespace std;
#include 

//定义类模板MyArry
template
class MyArry {

public:
	//有参构造
	MyArry(int capacity) {...}
    
    //防止浅拷贝问题
	//拷贝构造
	MyArry(const MyArry& arr) {
		//cout 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 m_Size; i++) {
			this->pAddress[i] = arr.pAddress[i];
		}
	}
    
    //重载赋值运算符,防止出现浅拷贝问题
    //防止写连等号时(类似这种arr[10] = arr[3])报错,所以返回类型是MyArry&,要对MyArry对象进行操作
	MyArry& operator=(const MyArry& arr) {
		//cout pAddress != NULL) {
			delete[] this->pAddress;
			this->pAddress = NULL;
			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 m_Size; i++) {
			this->pAddress[i] = arr.pAddress[i];
		}
		return *this;//返回自身
	}

	//释放内存
	~MyArry() {...}

private:
	T* pAddress;//指针指向堆区开辟的真实数组

	int m_Capacity;//数组容量
	int m_Size;//数组大小
};
尾插法和尾删法CRUD

没什么好说的

//自定义通用数组类
#pragma once
#include
using namespace std;
#include 

//定义类模板MyArry
template
class MyArry {

public:
	//有参构造
	MyArry(int capacity) {...}
    
	//拷贝构造
	MyArry(const MyArry& arr) {...}
    
    //重载赋值运算符,防止出现浅拷贝问题
	MyArry& operator=(const MyArry& arr) {...}

    //尾插法
	//输入是T类型数据,且为了防止被修改,要const修饰
	void Push_Back(const T& val) {
		//判断容量是否等于大小
		if (this->m_Capacity == this->m_Size) {
			cout m_Size
		this->pAddress[this->m_Size] = val;
		this->m_Size++;//更新数组大小
	}
	//尾删法
	void Pop_Back() {
		//让用户访问不到最后一个元素即可,逻辑删除
		//判断当前数组是否还有数据
		if (this->m_Size == 0) {
			cout m_Size--;//屏蔽调对最后一个数的访问
	}
    
	//释放内存
	~MyArry() {...}

private:
	T* pAddress;//指针指向堆区开辟的真实数组

	int m_Capacity;//数组容量
	int m_Size;//数组大小
};
下标访问数组中元素

以及剩下的功能

//自定义通用数组类
#pragma once
#include
using namespace std;
#include 

//定义类模板MyArry
template
class MyArry {

public:
	//有参构造
	MyArry(int capacity) {...}
	//拷贝构造
	MyArry(const MyArry& arr) {...}
    
    //重载赋值运算符,防止出现浅拷贝问题
	MyArry& operator=(const MyArry& arr) {...}
    //尾插法
	//输入是T类型数据,且为了防止被修改,要const修饰
	void Push_Back(const T& val) {...}
	//尾删法
	void Pop_Back() {...}
    
    //通过下标的方式访问数组中的元素
	//如果调用完之后还想作为左值存在,即arr[0] = 100
	//返回类型应该是T的引用,返回数的本身
	T& operator[](int index) {

		//返回数组中index出的元素
		return this->pAddress[index];
		
	}

	//获取数组容量
	int getCapacity()
	{
		return this->m_Capacity;
	}

	//获取数组大小
	int	getSize()
	{
		return this->m_Size;
	}
    
    
	//释放内存
	~MyArry() {...}

private:
	T* pAddress;//指针指向堆区开辟的真实数组

	int m_Capacity;//数组容量
	int m_Size;//数组大小
};
完整代码
//自定义通用数组类
#pragma once
#include
using namespace std;
#include 


template
class MyArry {

public:
	//有参构造
	MyArry(int capacity) {
		//cout m_Capacity = capacity;
		this->m_Size = 0;
		this->pAddress = new T[this->m_Capacity];
	}

	//防止浅拷贝问题
	//拷贝构造
	MyArry(const MyArry& arr) {
		//cout 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 m_Size; i++) {
			this->pAddress[i] = arr.pAddress[i];
		}
	}

	//重载赋值运算符,防止出现浅拷贝问题
	MyArry& operator=(const MyArry& arr) {//防止写连等号时报错,所以返回类型是MyArry&
		//cout pAddress != NULL) {
			delete[] this->pAddress;
			this->pAddress = NULL;
			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 m_Size; i++) {
			this->pAddress[i] = arr.pAddress[i];
		}
		return *this;//返回自身
	}

	//尾插法
	//输入是T类型数据,且为了防止被修改,要const修饰
	void Push_Back(const T& val) {
		//判断容量是否等于大小
		if (this->m_Capacity == this->m_Size) {
			cout m_Size
		this->pAddress[this->m_Size] = val;
		this->m_Size++;//更新数组大小
	}

	//尾删法
	void Pop_Back() {
		//让用户访问不到最后一个元素即可,逻辑删除
		//判断当前数组是否还有数据
		if (this->m_Size == 0) {
			cout m_Size--;//屏蔽调对最后一个数的访问
	}


	//通过下标的方式访问数组中的元素
	//如果调用完之后还想作为左值存在,即arr[0] = 100
	//返回类型应该是T的引用,返回数的本身
	T& operator[](int index) {

		//返回数组中index出的元素
		return this->pAddress[index];
		
	}

	//获取数组容量
	int getCapacity()
	{
		return this->m_Capacity;
	}

	//获取数组大小
	int	getSize()
	{
		return this->m_Size;
	}



	//涉及在堆中开辟空间,要写一下析构函数
	//释放内存
	~MyArry() {
		//cout pAddress != NULL) {
			delete[] this->pAddress;
			this->pAddress = NULL;//防止野指针
		}
	}

private:
	T* pAddress;//指针指向堆区开辟的真实数组

	int m_Capacity;//数组容量
	int m_Size;//数组大小
};

类模板-通用数组类.cpp

在该类中进行调用测试(自定义类的就不测了,懒)

#include
using namespace std;
#include 
#include "MyArray.hpp"

void printIntArray(MyArry& arr){
	for (int i = 0; i  arr1(5);
	/*MyArry arr2(arr1);
	MyArry arr3(15);*/
	//arr3 = arr1;

	for (int i = 0; i  arr2(arr1);
	arr2.Pop_Back();
	cout 

文章来源于互联网:【C++ 泛型编程01:模板】函数模板与类模板

THE END
分享
二维码