【C++】模板

模板的特点:
模板不可以直接使用,它只是一个框架;模板的通用并不是万能的。

1. 函数模板

C++另一种编程思想称为泛型编程,主要利用的技术就是模板;
C++提供两种模板机制:函数模板和类模板。

1.1函数模板语法

【语法】
template < typename T>
函数声明或定义
【解释】
template——声明创建模板
typename——表明其后面的符号是一种数据模型,可以用class代替
T——通用的数据类型,名称可以替换,通常为大写字母

【代码示例】

#include <iostream>
using namespace std;


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

template<typename T> //声明一个模板
void mySwap(T& a, T& b)//类型参数化
{
	T temp = a;
	a = b;
	b = temp;
}


int main()
{
	int a = 10;
	int b = 20;
	cout << "befor a=" << a << ", b=" << b << endl;
	//swapInt(a, b);
	//两种方式使用函数模板
	//1. 自动类型推导
	mySwap(a, b);
	cout << "after a=" << a << ", b=" << b << endl;

	float c = 10.1;
	float d = 20.1;
	cout << "befor c=" << c << ", d=" << d << endl;
	//swapFloat(c, d);
	//2.显示指定类型
	mySwap<float>(c, d);
	cout << "after c=" << c << ", d=" << d << endl;
	return 0;
}

1.2 函数模板注意事项

注意事项:

  1. 自动类型推导,必须推导出一致的数据类型T才可以使用
  2. 模板必须确定出T的数据类型才可以使用
    【代码示例】
#include <iostream>
using namespace std;

template<class T>
void mySwap(T& a, T& b)
{
	T temp = a;
	a = b;
	b = temp;
}

template<typename T>
void func()
{

}

int main()
{
	int a = 10;
	int b = 20;
	char c = 'A';
	mySwap(a, b);
	//1. 自动类型推导,必须推导出一致的数据类型T才可以使用
	//mySwap(a, c);error 没有与参数列表匹配的函数模板“mySwap”实例,参数类型为: (int, char)	
	cout << "a=" << a << ", b=" << b;
	//2. 模板必须确定出T的数据类型才可以使用
	func<void>();
	return 0;
}

1.3 函数模板案例

【案例描述】

  1. 利用函数模板封装一个排序的函数,可以对不同数据类型数组进行排序
  2. 排序规则从大到小,排序算法为选择排序
  3. 分别利用char数组和int数组进行测试
    【实现代码】
#include <iostream>
using namespace std;

template<typename T>
void mySwap(T& a, T& b)
{
	T temp = a;
	a = b;
	b = temp;
}

template<typename T>
void mySelectSort(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[i], arr[max]);
		}

	}
}

template<typename T>
void myPrint(T* arr, int len)
{
	for (int i = 0; i < len; i++)
	{
		cout << arr[i] << " ";
	}
	cout << endl;
}

int main()
{
	//char arr[] = "abcde";
	int arr[] = { 1, 2, 3,4,5 };
	int len = sizeof(arr) / sizeof(int);
	cout << "len=" << len << endl;
	myPrint<int>(arr, len);
	mySelectSort<int>(arr, len);
	myPrint<int>(arr, len);

	char c[] = "cbade";
	int len1 = sizeof(c) / sizeof(char) - 1;
	cout << "len1=" << len1 << endl;
	myPrint<char>(c, len1);
	mySelectSort<char>(c, len1);
	myPrint<char>(c, len1);
	return 0;
}

1.4 普通函数与函数模板的区别

【区别】

  • 普通函数调用时可以发生自动类型转换(隐式类型转换)
  • 函数模板调用时,如果利用自动类型推导,不会发生隐式类型转换
  • 如果利用显式指定类型的方式,可以发生隐式类型转换
    【代码示例】
#include <iostream>
using namespace std;

//普通函数
int myAdd(int a, int b)
{
	return a + b;
}

template<typename T>
T myAdd2(T a, T b)
{
	return a + b;
}

int main()
{
	int a = 10;
	int b = 20;
	cout << myAdd(a, b) << endl;
	char c = 'A';
	cout << myAdd(a, c) << endl;

	cout << myAdd2(a, b) << endl;
	//cout << myAdd2(a, c) << endl; 没有与参数列表匹配的函数模板“myAdd2"实例,参数类型为: (int, char)
	cout << myAdd2(a, (int)c) << endl;

	return 0;
}

1.5 普通函数与函数模板的调用规则

调用规则如下:

  1. 如果函数模板和普通函数都可以实现,优先调用普通函数
  2. 可以通过空模板参数列表来强制调用函数模板
  3. 函数模板也可以发生重载
  4. 如果函数模板可以产生更好的匹配,优先调用函数模板
    【代码示例】
#include <iostream>
using namespace std;

//普通函数
int myAdd(int a, int b)
{
	return a + b;
}

template<typename T>
T myAdd(T a, T b)
{
	return a + b;
}

template<typename T>
T myAdd(T a, T b, T c)
{
	return a + b + c;
}

int main()
{
	int a = 10;
	int b = 20;
	cout << myAdd(a, b) << endl;
	char c = 'A';
	char d = 'B';
	cout << myAdd(a, c) << endl;

	//通过空模板参数列表,强制调用函数模板
	cout << myAdd<>(a, b) << endl;
	//cout << myAdd2(a, c) << endl; 没有与参数列表匹配的函数模板“myAdd2"实例,参数类型为: (int, char)
	cout << myAdd<>(a, (int)d) << endl;
	//函数重载
	cout << myAdd<>(a, b, (int)c) << endl;

	cout << myAdd(' ', c) << endl;
	return 0;
}

1.6 模板的局限性

模板并不是万能的,有些特定数据类型需要具体化方式做特殊实现
【代码实现】

#include <iostream>
using namespace std;

template<typename T>
bool myCompare(T a, T b)
{
	if (a == b)
	{
		return true;
	}
	return false;
}

class Person
{
public:

	Person(string name, int age)
	{
		this->name = name;
		this->age = age;
	}
	string name;
	int age;
};

//利用具体化Person的版本实现代码,具体化优先调用
template<> bool myCompare(Person& p1, Person& p2)//模板函数的重载
{
	if (p1.name == p2.name && p1.age == p2.age)
	{
		return true;
	}
	return false;
}

int main()
{
	int a = 10;
	int b = 20;
	cout << "a==b? " << myCompare(a, b) << endl;

	Person p1("zhangsan", 18);
	Person p2("lisi", 20);
	cout << "p1==p2? " << myCompare(a, b) << endl;

	return 0;
}
  • 利用具体化的模板,可以解决自定义类型的通用化
  • 学习模板不是为了写模板,而是在STL能够运用系统提供的模板

2. 类模板

2.1 类模板语法

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

语法:
template< typename T>
template——声明模板,typename——表明其后面的符号是一种数据类型,可以用class代替,T——通用数据类型,名称可以替换,通常为大写字母。

【代码示例】

#include <iostream>
using namespace std;

template<class NameType, class AgeType>
class Person
{
public:

	Person(NameType name, AgeType age)
	{
		this->name = name;
		this->age = age;
	}
	void show()
	{
		cout << "name=" << this->name << " age=" << this->age << endl;
	}
	NameType name;
	AgeType age;
};
int main()
{
	Person<string, int> p1("张三", 18);
	p1.show();
	return 0;
}

3.2 类模板与函数模板的区别

【区别】

  • 类模板没有自动类型推导的使用方式
  • 类模板在模板参数列表中可以有默认参数
    【代码示例】
#include <iostream>
using namespace std;

//类模板在模板参数列表中有默认参数
template<class NameType, class AgeType = int>
class Person
{
public:

	Person(NameType name, AgeType age)
	{

		this->name = name;
		this->age = age;
	}
	void show()
	{
		cout << "name=" << this->name << " age=" << this->age << endl;
	}
	NameType name;
	AgeType age;
};
int main()
{
	Person<string, int> p1("张三", 20);
	p1.show();
	return 0;
}

2.3 类模板中成员函数创建时机

类模板中成员函数和普通类成员函数创建时机是有区别的:

  • 普通类中的成员函数一开始就可以创建
  • 类模板中的成员函数在调用时才创建
    【代码示例】
#include <iostream>
using namespace std;


class Person1
{
public:
	void showPerson1()
	{
		cout << "Person1" << endl;
	}
};

class Person2
{
public:
	void showPerson2()
	{
		cout << "Person2" << endl;
	}
};

template<typename T>
class MyClass
{
public:

	T obj;
	//未调用前不会创建
	void func1()
	{
		obj.showPerson1();
	}

	void func2()
	{
		obj.showPerson2();
	}

};
int main()
{
	MyClass<Person1> p1;
	p1.func1();
	//p1.func2();不是 "Person1" 的成员

	MyClass<Person2> p2;
	p2.func2();
	//p2.func1();不是 "Person2" 的成员
	return 0;
}

2.4 类模板对象做函数参数

三种传入方式:

  1. 指定传入的类型——直接显示对象的数据类型(最常用)
  2. 参数类模板化——将对象的参数变为模板进行传递
  3. 整个类模板化——将这个对象类型模板化进行传递
    【代码示例】
#include <iostream>
using namespace std;

template<class T1, class T2>
class Person
{
public:

	Person(T1 name, T2 age)
	{
		mName = name;
		mAge = age;
	}
	void show()
	{
		cout << "name=" << mName << " age=" << mAge << endl;
	}
	T1 mName;
	T2 mAge;
};
//指定传入的类型——直接显示对象的数据类型
void myPrint1(Person<string, int>& p)
{
	p.show();
}
//参数类模板化——将对象的参数变为模板进行传递
template<class T1, class T2>
void myPrint2(Person<T1, T2>& p)
{
	p.show();
	cout << "T1的类型:" << typeid(T1).name() << endl;
	cout << "T2的类型:" << typeid(T2).name() << endl;
}
//整个类模板化——将这个对象类型模板化进行传递
template<class T>
void myPrint3(T& p)
{
	p.show();
	cout << "T的类型:" << typeid(T).name() << endl;
}
int main()
{
	Person<string, int> p1("张三", 18);
	myPrint1(p1);
	myPrint2(p1);
	myPrint3(p1);
	return 0;
}

2.5 类模板与继承

当类模板碰到继承时,需注意:

  1. 当子类继承的父类是一个类模板时,子类在声明时,要指定出父类中T的类型
  2. 如果不指定,编译器无法给子类分配内存
  3. 如果想灵活指定出父类中T的类型,子类也需变为类模板
    【代码示例】
#include <iostream>
using namespace std;

template<class T>
class Base
{
public:
	T m;
};

//子类在声明时,要指定出父类中T的类型
class Son1 :public Base<int>
{
public:
	void show()
	{
		cout << "指定出父类中T的类型" << endl;
	}
};

//如果想灵活指定出父类中T的类型,子类也需变为类模板
template<class T1, class T2>
class Son2 :public Base<T2>
{
public:
	T1 obj;
	void show()
	{
		cout << "子类变为类模板" << endl;
		cout << "T1的类型:" << typeid(T1).name() << endl;
		cout << "T2的类型:" << typeid(T2).name() << endl;
	}
};
int main()
{
	Son1 s1;
	s1.show();
	Son2<char, int> s2;
	s2.show();
	return 0;
}

2.6 类模板成员函数的类外实现

【代码示例】

类模板中成员函数的类外实现,需要加上模板参数列表。

#include <iostream>
using namespace std;

template<class T1, class T2>
class Person
{
public:

	Person(T1 name, T2 age);
	/*{
		mName = name;
		mAge = age;
	}*/
	void show();
	/*{
		cout << "name=" << mName << " age=" << mAge << endl;
	}*/
	T1 mName;
	T2 mAge;
};

template<class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age)
{
	mName = name;
	mAge = age;
}

template<class T1, class T2>
void Person<T1, T2>::show()
{
	cout << "name=" << mName << " age=" << mAge << endl;
}
int main()
{
	Person<string, int> p("张三",18);
	p.show();
	return 0;
}

2.7 类模板份文件编写

问题:类模板中成员函数的创建时机是在调用阶段,导致分文件编写时链接不到
解决:方式1:直接包含.cpp文件;方式2(主流的方式):将声明和实现写到同一文件中,并更改后缀名为.hpp,hpp是约定名称,不是强制
【代码示例】
【person.hpp】

#pragma once
#include <iostream>
using namespace std;

template<class T1, class T2>
class Person
{
public:

	Person(T1 name, T2 age);
	void show();
	T1 mName;
	T2 mAge;
};

template<class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age)
{
	mName = name;
	mAge = age;
}

template<class T1, class T2>
void Person<T1, T2>::show()
{
	cout << "name=" << mName << " age=" << mAge << endl;
}

【main函数】

#include <iostream>
using namespace std;
#include "person.hpp"

int main()
{
	Person<string, int> p("张三",18);
	p.show();
	return 0;
}

2.8 类模板与友元

全局函数类内模板——直接在类内声明友元即可
全局函数类外实现——需要提前让编译器知道全局函数的存在

【代码示例】

#include <iostream>
using namespace std;

//类外实现
template<class T1, class T2>
class Person;

template<class T1, class T2>
void printPerson2(const Person<T1, T2>& p)
{
	cout << "name=" << p.mName << " age=" << p.mAge << endl;
}
template<class T1, class T2>
class Person
{
	//加空参数列表
	//如果是全局函数是类外实现,需要让编译器提前知道这个函数的存在
	//如果是全局函数是类外实现,需要让编译器提前知道这个函数的存在
	friend void printPerson2<>(const Person<T1, T2>& p);

	/*friend void printPerson(const Person<T1, T2> &p)
	{
		cout << "name=" << p.mName << " age=" << p.mAge << endl;
	}*/

public:

	Person(T1 name, T2 age)
	{
		mName = name;
		mAge = age;
	}

private:
	T1 mName;
	T2 mAge;
};


int main()
{
	Person<string, int> p("张三", 18);
	//printPerson(p);
	printPerson2(p);
	return 0;
}

2.9 类模板案例

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

  • 可以对内置数据类型以及自定义数据类型的数据进行存储
  • 将数组中的数据存储到堆区
  • 构造函数中可以传入数组的容量
  • 提供对应的拷贝构造函数以及operator=防止浅拷贝问题
  • 提供尾插法和尾删法对数组中的数据进行增加和删除
  • 可以通过下标的方式访问数组中的元素
  • 可以获取数组中当前元素个数和数组的容量
    【实现代码】
    【MyArray.hpp】
#pragma once
#include <iostream>
using namespace std;

template<class T>
class myArray
{
public:

	//构造函数中可以传入数组的容量
	myArray(int c)
	{
		//cout << "有参构造函数调用" <<endl;
		this->capacity = c;
		this->size = 0;
		this->arr = new T[this->capacity];//这里需要有T(Person)的默认构造
	}
	~myArray()
	{
		//cout << "析构函数调用" << endl;
		if (this->arr != NULL)
		{
			//cout << "释放成功" << endl;
			delete[] this->arr; //数组释放
			this->arr = NULL;
		}
	}
	//拷贝构造函数
	myArray(const myArray& m)
	{
		//cout << "拷贝函数调用" << endl;
		this->capacity = m.capacity;
		this->size = m.size;
		//this->arr = m.arr; //浅拷贝

		this->arr = new T[this->capacity];
		//将原数组的数据拷贝
		for (int i = 0; i < this->size; i++)
		{
			this->arr[i] = m.arr[i];
		}

	}
	//防止浅拷贝 a=b=c的问题
	myArray& operator=(const myArray& m)
	{
		//cout << "赋值重载函数调用" << endl;
		if (this->size != 0)
		{
			delete[]this->arr;
			this->arr = NULL;
			this->capacity = 0;
			this->size = 0;
		}
		this->capacity = m.capacity;
		this->size = m.size;
		this->arr = new T[this->capacity];
		//将原数组的数据拷贝
		for (int i = 0; i < this->size; i++)
		{
			this->arr[i] = m.arr[i];
		}
		return *this;
	}
	//提供尾插法对数组中的数据进行增加
	bool add(const T& data)
	{
		if (this->size < this->capacity)
		{
			this->arr[size] = data;
			this->size++;
			return true;
		}
		return false;
	}
	//尾删法对数组中的数据进行删除
	bool del()
	{
		if (this->size > 0)
		{
			this->size--;
			return true;
		}
		return false;
	}
	//通过下标的方式访问数组中的元素
	T& operator[](int index)
	{
		return this->arr[index];
	}
	//可以获取数组中当前元素个数
	int getSize()
	{
		return this->size;
	}
	//获取数组的容量
	int getCapacity()
	{
		return this->capacity;
	}
private:
	T* arr;//指针指向堆区开辟的数组
	int capacity;//容量
	int size;//大小
};

【main函数】

#include <iostream>
using namespace std;
#include "MyArray.hpp"

template<typename T>
void printArray(myArray<T>& m)//这里不能写const myArray<T> &m
{
	for (int i = 0; i < m.getSize(); i++)
	{
		cout << m[i] << endl;
	}
}


//测试自定义数据
class Person
{
public:
	Person() {}//在类模板的构造函数中new T[this->capacity]需要用到默认构造创建
	//不写则会报错 C2512	“Person”: 没有合适的默认构造函数可用,在MyArray.hpp的16行
	Person(string name, int age)
	{
		this->name = name;
		this->age = age;
	}
	string name;
	int age;
};

void printPersonArray(myArray<Person>& p)
{
	for (int i = 0; i < p.getSize(); i++)
	{
		cout << "name=" << p[i].name << " age=" << p[i].age << endl;
	}
}

int main()
{
	myArray<int> arr1(5);
	//myArray<int> arr2(arr1);
	//myArray<int> arr3(100);
	//arr3 = arr1;
	for (int i = 0; i < 5; i++)
	{
		arr1.add(i + 10);
	}
	printArray(arr1);
	cout << endl;
	cout << "capacity=" << arr1.getCapacity() << " size=" << arr1.getSize() << endl;
	cout << arr1[0] << endl;
	arr1.del();
	cout << endl;
	cout << "capacity=" << arr1.getCapacity() << " size=" << arr1.getSize() << endl;
	printArray(arr1);


	myArray<Person> arr2(10);
	Person p1("孙悟空", 100);
	Person p2("猪八戒", 90);
	Person p3("唐僧", 80);
	Person p4("国王", 70);
	Person p5("妖怪", 10);

	arr2.add(p1);
	arr2.add(p2);
	arr2.add(p3);
	arr2.add(p4);
	arr2.add(p5);

	printPersonArray(arr2);

	cout << "size=" << arr2.getSize() << endl;
	arr2.del();
	cout << "size=" << arr2.getSize() << endl;
	cout << "capacity=" << arr2.getCapacity() << endl;

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值