C++学习路线之C++基础(九)——模板及其使用

本章开始对C++泛型编程和STL技术做详细讲解。 

十二、模板

模板:建立通用的模具,提高复用性。.

  • 模板不可以直接使用,只是一个框架
  • 模板的通用不是万能的

C++模板分为函数模板和类模板两类。

12.1、函数模板

函数模板的作用:其函数返回值类型和形参类型可以不具体指定,使用一个虚拟的类型来代表。

语法:

template<typename T>

函数声明或定义

#include<iostream>

using namespace std;

template<typename 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);
	//方法2、显示指定类型
	myswap<int>(a, b);
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	double c = 1.2;
	double d = 2.2;
	myswap(c, d);
	cout << "c = " << c << endl;
	cout << "d = " << d << endl;
}

int main()
{
	test01();
	return 0;
}

12.1.2、函数模板注意事项

  • 自动类型推导,必须推导出一致的数据类型T才可以使用
  • 模板必须要确定出T的类型才可以使用
#include<iostream>

using namespace std;

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

void test01()
{
	int a = 10;
	int b = 20;
	myswap(a, b);
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	char c = 'c';
	//myswap(a, c);//错误!推导不出一致T类型
}

template<class T>
void func()
{
	cout << "use func()" << endl;
}

void test02()
{
	func<int>();//必须显示指明T类型
}

int main()
{
	test01();
	test02();
	return 0;
}

12.1.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 choiceSort(T* arr,int len)
{
	for (int i = 0; i < len; i++)
	{
		int min = i;
		for (int j = i+1; j < len; j++)
		{
			if (arr[min] > arr[j])//更新min值
			{
				min = j;
			}
		}
		if (min != i)
		{
			myswap(arr[min], arr[i]);
		}
	}
}
template<typename T>
void myprint(T* arr, int len)
{
	for (int i = 0; i < len; i++)
	{
		cout << arr[i] << "-";
	}
	cout << endl;
}
void test01()
{
	int arri[] = { 9,8,7,6,5,4,3,2,1 };
	int len = sizeof(arri) / sizeof(arri[0]);
	choiceSort<int>(arri, len);
	myprint<int>(arri, len);
}

void test02()
{
	char charArr[] = "helloworlddsafsfwf";
	int len = sizeof(charArr) / sizeof(charArr[0]);
	choiceSort(charArr, len);
	cout << len << endl;
	myprint(charArr, len);
}

int main()
{
	test01();
	test02();
	return 0;
}

12.1.4、普通函数和函数模板的区别

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

using namespace std;

//普通函数
int myadd01(int a, int b)
{
	return a + b;
}
template<typename T>
T myadd02(T a, T b)
{
	return a + b;
}

void test01()
{
	int a = 10;
	int b = 20;
	char c = 'c';//c的ASCII码为99
	cout << myadd01(a, c) << endl;
	cout << myadd02(a, b) << endl;
	//cout << myadd02(a, c) << endl;//无法推导一致的类型
	cout << myadd02<int>(a, c) << endl;
}

int main()
{
	test01();
	return 0;
}

12.1.5、普通函数与函数模板调用规则

调用规则如下:
1.如果函数模板和普通函数都可以实现,优先调用首通函数

2.可以通过空模板参数列表来强制调用函数模板
3.函数模板也以发生重载
4.如果函数模板可以产生更好的匹配,优先调用函数模板

#include<iostream>

using namespace std;

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, b = 20;
	myprint(a, b);//优先调用普通函数,如果被普通函数定义被注释,报错
	myprint<>(a, b);//强制调用函数模板
	myprint(a, b, 100);//函数模板重载
	char c1 = 'a';
	char c2 = 'b';
	myprint(c1, c2);//调用函数模板
}

int main()
{
	test01();
	return 0;
}

12.1.6、模板的局限性

模板的使用是由局限的,

C++可以对特定的类型提供具体化的模板

#include<iostream>
#include<string>
using namespace std;

class person
{
public:
	int myage;
	string myname;
	person(int age, string name)
	{
		myage = age;
		myname = name;
	}
};

template<typename T>
bool myCompare(T& a, T& b)
{
	return (a == b);//可以使用运算符重载解决,
}

//利用具体化的person的版本来实现代码,具体化优先调用
template<> bool myCompare(person &p1, person &p2)
{
	if (p1.myage == p2.myage && p1.myname == p2.myname)
	{
		return true;
	}
	else
	{
		return false;
	}
}

void test01()
{
	int a = 10;
	int b = 20;
	bool ret = myCompare(a, b);
	if (ret)
	{
		cout << "a = b" << endl;
	}
	else
	{
		cout << "a!=b" << endl;
	}
}

void test02()
{
	person p1( 10, "tom");
	person p2(10, "tom");
	bool ret = myCompare(p1, p2);
	if (ret)
	{
		cout << "p1 = p2" << endl;
	}
	else
	{
		cout << "p1!=p2" << endl;
	}
}

int main()
{
	test01();
	test02();
	return 0;
}

12.2、类模板

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

语法:template<class T>

#include<iostream>
#include<string>
using namespace std;
//类模板
template <class NameType,class AgeType>
class Person
{
public:
	NameType m_Name;
	AgeType m_Age;
	Person(NameType name,AgeType age)
	{
		this->m_Age = age;
		this->m_Name = name;
	}
	void showPerson()
	{
		cout << "name = " << this->m_Name << endl;
		cout << "age = " << this->m_Age << endl;
	}
};

void test01()
{
	Person<string, int> p1("老孙", 999);

	p1.showPerson();
}

int main()
{
	test01();
	return 0;
}

12.2.1、类模板和函数模板区别

  1. 类模板没有自动推导的使用方式,必须显示指定
  2. 类模板在模板参数列表中可以有默认参数
#include<iostream>
#include<string>
using namespace std;
//类模板
template <class NameType, class AgeType = int>//AgeType可以默认为int
class Person
{
public:
	NameType m_Name;
	AgeType m_Age;
	Person(NameType name, AgeType age)
	{
		this->m_Age = age;
		this->m_Name = name;
	}
	void showPerson()
	{
		cout << "name = " << this->m_Name << endl;
		cout << "age = " << this->m_Age << endl;
	}
};

void test01()
{
	Person<string, int> p1("老孙", 999);
	//Person p("老孙", 1000);//无法用自动类型推导
	p1.showPerson();
}

void test02()
{
	Person<string> p("老猪", 100);
	p.showPerson();
}

int main()
{
	test01();
	test02();
	return 0;
}

12.2.2、类模板成员函数创建时机

普通类成员函数一开始就可以创建。类模板成员函数调用时才创建。

#include<iostream>

using namespace std;

class person1
{
public:
	void showperson1()
	{
		cout << "show person1" << endl;
	}
};

class person2
{
public:
	void showperson2()
	{
		cout << "show person2" << endl;
	}
};
template<class T>
class myClass
{
public:
	T obj;
	//类模板成员函数
	void func1()
	{
		obj.showperson1();//不调用的时候不创建
	}
	void func2()
	{
		obj.showperson2();
	}
};

void test01()
{
	myClass<person1> m;
	m.func1();
	//m.func2();//调用的时候创建,func2()没有调用,不会创建,不会报错
}

int main()
{
	test01();
	return 0;
}

12.2.3、类模板对象做函数参数

三种方式:1指定传入的类型2参数模板化。3类模板化

#include<iostream>
#include<string>
using namespace std;

template<class T1,class T2>
class person
{
public:
	T1 m_name;
	T2 m_age;
	person(T1 name, T2 age)
	{
		this->m_age = age;
		this->m_name = name;
	}
	void showperson()
	{
		cout << "name :" << this->m_name << ",age = " << this->m_age << endl;
	}
};
//指定传入类型
void printperson1(person<string, int>& p)
{
	p.showperson();
}

//参数模板化
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;
}

//整个类模板化
template<class T>
void printperson3(T &p)
{
	p.showperson();
	cout << "T的类型为" << typeid(T).name() << endl;
}


void test01()
{
	person<string, int> p("孙悟空", 100);
	printperson1(p);
}

void test02()
{
	person<string, int> p("猪八戒", 90);
	printperson2(p);
}

void test03()
{
	person<string, int> p("唐僧", 30);
	printperson3(p);
}

int main()
{
	test01();
	test02();
	test03();
	return 0;
}

12.2.4、类模板与继承

  • 子类继承的父亲是一个类模板时,子类在声明的时候,需要指定出父类T的类型
  • 如果不指定,编译器无法给子类分配内存
  • 如果想要灵活指出父类T的类型,子类也应该变成类模板。
#include<iostream>

using namespace std;
template<class T>
class Base
{
	T m;
};
//方法1 指明T的类型
class Son1 :public Base<int>
{

};
//方法2 子类模板化
template<class T1,class T2>
class Son2 :public Base<T2>
{
public:
	Son2()
	{
		cout << typeid(T1).name() << endl;
		cout << typeid(T2).name() << endl;
	}
	T1 obj;
};


void test02()
{
	Son2<int, char> s2;
}


int main()
{
	test02();
	return 0;
}

12.2.5、类模板成员函数类外实现

#include<iostream>
#include<string>

using namespace std;

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", 90);
	p.showperson();
}

int main()
{
	test01();
	return 0;
}

12.2.6、类模板分文件编写

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

解决方法:

  • 直接包含.cpp源文件

person.h

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

template<class T1, class T2>
class person
{
public:
	person(T1 name, T2 age);
	void showperson();
	T1 m_name;
	T2 m_age;
};

person.cpp

#include"person.h"

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;
}

 main.cpp

#include<iostream>
#include<string>
#include"person.cpp"//.h变成.cpp

using namespace std;

void test01()
{
	person<string, int> p("Tom", 90);
	p.showperson();
}

int main()
{
	test01();
	return 0;
}
  • 将声明和实现写在同一个文件中,并更改后缀名为.hpp,.hpp是约定的名称(将.j和cpp中内容写在一起)

person.hpp

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

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;
}

main.cpp

#include<iostream>
#include<string>
#include"person.hpp"

using namespace std;

void test01()
{
	person<string, int> p("Tom", 90);
	p.showperson();
}

int main()
{
	test01();
	return 0;
}

12.2.7、类模板与友元

#include<iostream>
#include<string>
using namespace std;

template<class T1, class T2>
class person;
template <class T1, class T2>
void printperson2(person<T1, T2> p);//要先声明person类存在。

template<class T1, class 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_age = age;
		this->m_name = name;
	}
	
private:
	T1 m_name;
	T2 m_age;
};

template <class T1,class T2>
void printperson2(person<T1, T2> p)
{
	cout << p.m_name << "的年龄是" << p.m_age << endl;
}

void test01()
{
	person<string, int> p("tom", 20);
	printperson(p);
	printperson2(p);
}

int main()
{
	test01();
	return 0;
}

12.2.8、类模板案例——数组的封装

  

 myArray.hpp

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

template<class T>
class Myarray
{
	int m_num;//容量
	int m_size;
	T* arrAddress;
public:
	//有参构造
	Myarray(int num);
	//拷贝构造
	Myarray(Myarray &arr1);
	//等号的重构
	Myarray& operator=(const Myarray& arr);
	//利用下标访问数组元素
	T operator[](int i);
	//尾插法
	void Push_Back(const T& value);
	//尾删法
	void Pop_back();
	//获取数组大小
	int getSize();
	//获取数组容量
	int getNum();
	//析构
	~Myarray();
};
//有参构造
template <class T>
Myarray<T>::Myarray(int num)
{
	//cout << "有参构造" << endl;
	this->m_num = num;
	this->arrAddress = new T[num];
	this->m_size = 0;
}
//拷贝构造
template <class T>
Myarray<T>::Myarray(Myarray &arr)
{
	//cout << "拷贝构造" << endl;
	this->m_num = arr.m_num;
	this->m_size = arr.m_size;
	//深拷贝
	this ->arrAddress = new T[arr.m_num];
	//arr数据拷贝
	for (int i = 0; i < this->m_size; i++)
	{
		this->arrAddress[i] = arr.arrAddress[i];
	}
}
//等号的重载
template <class T>
Myarray<T>& Myarray<T>::operator=(const Myarray& arr)
{
	//cout << "等号重载" << endl;
	//先判断原来堆区是否有数据
	if (this->arrAddress != NULL)
	{
		delete[] this->arrAddress;
		this->m_num = 0;
		this->m_size = 0;
	}
	this->m_num = arr.m_num;
	this->m_size = arr.m_size;
	//深拷贝
	this->arrAddress = new T[arr.m_num];
	//arr数据拷贝
	for (int i = 0; i < this->m_size; i++)
	{
		this->arrAddress[i] = arr.arrAddress[i];
	}
	return *this;
}

//利用下标访问数组元素——重载中括号
template <class T>
T Myarray<T>:: operator[](int i)
{
	if (i < this->m_size)
	{
		return this->arrAddress[i];
	}
	else
	{
		cout << "当前位置没有数据或者无法访问" << endl;
	}
}

//尾插法
template <class T>
void Myarray<T>::Push_Back(const T& value)
{
	if (this->m_num == this->m_size)
	{
		cout << "数组已满,无法插入" << endl;
		return;
	}
	this->arrAddress[this->m_size] = value;
	this->m_size++;
}

//尾删法
template <class T>
void  Myarray<T>::Pop_back()
{
	if (this->m_size == 0)
	{
		cout << "数组为空" << endl;
		return;
	}
	this->m_size--;
}

//获取数组容量
template <class T>
int Myarray<T>::getNum()
{
	return this->m_num;
}
//获取数组大小-sizeof(T)*size
template <class T>
int Myarray<T>::getSize()
{
	return this->m_size;
}
//析构
template <class T>
Myarray<T>::~Myarray()
{
	if (this->arrAddress != NULL)
	{
		//cout << "析构函数" << endl;
		delete[] this->arrAddress;
		this->arrAddress = NULL;
		this->m_num = 0;
		this->m_size = 0;
	}
}

main.cpp

#include"myArray.hpp"
#include<string>
template<class T>
void printArr(Myarray<T> &arr)
{
	for (int i = 0; i < arr.getSize();i++)
	{
		cout << arr[i];
	}
	cout << endl;
}

void test01()
{
	Myarray<int> arr1(5);
	Myarray<int> arr2(arr1);
	//Myarray<int> arr3(100);
	for (int i = 0; i < arr1.getNum(); i++)
	{
		arr1.Push_Back(i);//尾插
	}
	arr1.Push_Back(6);//已满
	arr2 = arr1;
	printArr<int>(arr1);
	printArr<int>(arr2);
	for (int i = 0; i < arr2.getNum(); i++)
	{
		arr2.Pop_back();//尾删
	}
	arr2.Pop_back();//已空
	cout << arr2[9] << endl;
}

//测试自定义数据类型
class person
{
public:
	person() {};
	person(string name, int age)
	{
		this->m_age = age;
		this->m_name = name;
	}
	string m_name;
	int m_age;
};

void printpersonarr(Myarray<person> &arr)
{
	for (int i = 0; i < arr.getSize(); i++)
	{
		cout << arr[i].m_name << "的年龄是" << arr[i].m_age << endl;
	}
}

void test02()
{
	Myarray<person> arr(5);
	person p1("孙悟空", 10);
	person p2("李白", 15);
	person p3("赵云", 20);
	person p4("韩信", 25);
	person p5("妲己", 30);
	arr.Push_Back(p1);
	arr.Push_Back(p2);
	arr.Push_Back(p3);
	arr.Push_Back(p4);
	arr.Push_Back(p5);
	arr.Push_Back(p1);
	printpersonarr(arr);
	arr.Pop_back();
	arr.Pop_back();
	arr.Pop_back();
	arr.Pop_back();
	arr.Pop_back();
	arr.Pop_back();
}

int main()
{
	//test01();
	test02();
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值