C++提高编程——1 模板

模板

1 模板的概念

​ 模板就是建立通用的模具,大大提高复用性

模板的特点:

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

2 函数模板

  • C++另一种编程思想称为泛型编程,主要利用的技术就是模板
  • C++提供两种模板机制:函数模板类模板
2.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 swapDouble(double& a, double& b) {
	double temp = a;
	a = b;
	b = temp;
}

//函数模板
 //声明一个模板,告诉编译器后面代码紧跟着的T不要报错,是一个通用的数据类型
template<typename T>
void mySwap(T& a, T& b) {
	T temp = a;
	a = b;
	b = temp;
}

//测试
void test01() {
	int a = 10;
	int b = 20;
	swapInt(a, b);
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;

	double c = 1.1;
	double d = 2.2;
	swapDouble(c, d);
	cout << "c = " << c << endl;
	cout << "d = " << d << endl;

	//利用函数模板交换
	//两种方式使用函数模板
	//1、自动类型推导
	mySwap(a, b);
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	//2、显示指定类型
	mySwap<double>(c, d);
	cout << "c = " << c << endl;
	cout << "d = " << d << endl;
}

//主函数
int main() {
	test01();
	system("pause");
	return 0;
}

总结:

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

注意事项:

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

示例:

#include<iostream>
using namespace std;

//函数模板注意事项

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

//1、自动类型推导必须推导出一致的数据类型T才可以使用模板
void test01() {
	int a = 10;
	int b = 20;
	char c = 'c';
	mySwap(a, b);//正确
	//mySwap(a, c);//错误,推导出不一致的T类型
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
}

//2、模板必须要确定出T的数据类型,才可以使用
template<class T>
void func() {
	cout << "func调用" << endl;
}
void test02() {
	//func();没有确定T的数据类型
	func<int>();//正确
}

//主函数
int main() {
	test02();
	system("pause");
	return 0;
}
2.3 函数模板案例

案例描述:

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

示例:

#include <iostream>
using namespace std;

//实现通用 对数组进行排序的函数
//从大到小
//char 和 int

//交换函数模板
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) {
			//交换max和i下标元素
			mySwap(arr[max], arr[i]);
		}
	}
}

//提供打印数组模板
template<class T>
void PrintArr(T arr[],int len) {
	for (int i = 0; i < len; i++) {
		cout << arr[i] << " " ;
	}
	cout << endl;
}

void test01() {
	//测试char数组
	char charArr[] = "badcfe";
	int len = sizeof(charArr) / sizeof(char);
	mySort(charArr, len);
	PrintArr(charArr, len);
}

void test02() {
	//测试int数组
	int intArr[] = { 3,6,5,2,4,1,8,7,9 };
	int len = sizeof(intArr) / sizeof(int);
	mySort(intArr, len);
	PrintArr(intArr, len);
}

//主函数
int main() {
	test01();
	test02();
	system("pause");
	return 0;
}
2.4 普通函数与函数模板的区别

区别:

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

示例:

#include<iostream>
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 test01() {
	int a = 10;
	int b = 20;
	char c = 'c';//c => 99,ASCII
	cout << myAdd01(a, c) << endl;
	//自动类型推导,不会发生隐式类型转换
	//cout << myAdd02(a, c) << endl;//无法推导出一致的数据类型
	//显式指定类型,会发生隐式类型转换
	cout << myAdd02<int>(a, c) << endl;
}

//主函数
int main() {
	test01();
	system("pause");
	return 0;
}
2.5 普通函数与函数模板的调用规则

​ 调用规则如下:

  1. 如果函数模板和普通函数都可以实现,优先调用普通函数
  2. 可以通过空模板参数列表来强制调用函数模板
  3. 函数模板也可以发生重载
  4. 如果函数模板可以产生更好的匹配,优先调用函数模板
//普通函数与函数模板调用规则
void myPrint(int a, int b) {
	cout << "调用的普通函数" << endl;
}

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 test01() {
	//如果函数模板和普通函数都可以调用,优先调用普通函数
	myPrint(2, 3);
	//通过空模板参数列表,强制调用函数模板
	myPrint<>(2, 3);
	//函数模板也可以重载
	myPrint(2, 3, 4);
	//如果能产生更好的匹配,优先调用模板
	myPrint(2.2, 3.3);
	
}

//主函数
int main() {
	test01();
	system("pause");
	return 0;
}

总结:既然提供了函数模板,最好就不要提供普通函数,否则容易出现二义性

2.6 模板的局限性

局限性:

  • 模板的通用性并不是万能的

例如:

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++为了解决这种问题,提供模板的重载,可以为这些特定的类型提供具体化的模板

示例:

//模板的局限性
//模板并不是万能的,有些特定数据类型,需要用具体化方式做特殊实现

class Person {
public:
	string name;
	int age;
	Person(string name, int age) {
		this->name = name;
		this->age = 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.name == p2.name && p1.age == p2.age) {
		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("Tom", 20);
	Person p2("Tom", 20);

	bool ret = myCompare(p1, p2);
	if (ret) {
		cout << "p1 == p2" << endl;
	}
	else {
		cout << "p1 != p2" << endl;
	}
}

//主函数
int main() {
	test01();
	test02();
	system("pause");
	return 0;
}

总结:

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

3 类模板

3.1 类模板语法

​ 类模板作用

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

语法:

template<typename T>

解释:

template — 声明创建模板

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

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

//类模板
template<class NameType, class AgeType>
class Person {
public:
	NameType m_name;
	AgeType m_age;

	Person(NameType name, AgeType age) {
		this->m_name = name;
		this->m_age = age;
	}

	void showPerson() {
		cout << "name: " << m_name << endl;
		cout << "age = " << m_age << endl;
	}
};

void test01() {
	Person<string, int>p1("孙悟空", 999);
	p1.showPerson();
}

//主函数
int main() {
	test01();
	system("pause");
	return 0;
}

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

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

​ 区别:

  • 类模板没有自动类型推导的使用方式
  • 类模板在模板参数列表中可以有默认参数
//类模板与函数模板的区别

template<class NameType,class AgeType = int>
class Person {
public:
	NameType m_name;
	AgeType m_age;
	Person(NameType name, AgeType age) {
		this->m_name = name;
		this->m_age = age;
	}
	void showPerson() {
		cout << "name: " << m_name <<endl;
		cout << "sge = " << m_age <<endl;
	}
};

//类模板没有自动类型推导
void test01() {
	//Person p1("孙悟空", 999);//错误,无法用自动类型推导
	Person<string, int> p1("孙悟空", 999);
	p1.showPerson();
}

//类模板在模板参数列表中可以有默认参数
void test02() {
	Person<string> p1("猪八戒", 9999);
	p1.showPerson();
}

//主函数
int main() {
	test01();
	test02();
	system("pause");
	return 0;
}
3.3 类模板中成员函数创建时机

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

  • 普通类中的成员函数一开始就可以创建
  • 类模板中的成员函数在调用时才创建
//类模板中成员函数的调用时机

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

class Person2 {
public:
	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>m;
	m.func1();
	//m.func2();//编译会出错,说明函数调用才会去创建成员函数
}

//主函数
int main() {
	test01();
	system("pause");
	return 0;
}

总结:类模板中的成员函数并不是一开始就创建的,而是在调用时采取创建

3.4 类模板对象做函数参数

学习目标

  • 类模板实例化出的对象,像函数传参的方式

一共有三种传入方式:

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

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

	T1 m_name;
	T2 m_age;

	Person(T1 name, T2 age) {
		this->m_name = name;
		this->m_age = age;
	}

	void showPerson() {
		cout << "name: " << m_name << endl;
		cout << "age = " << m_age << endl;
	}
};

//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();
	cout << "T1的类型为:" << typeid(T1).name() << endl;
	cout << "T2的类型为:" << typeid(T2).name() << endl;
}

void test02() {
	Person<string, int>p2("猪八戒", 9999);
	printPerson2(p2);
}

//3、将整个类模板化
template<class T>
void printPerson3(T& p) {
	p.showPerson();
	cout << "T的数据类型:" << typeid(T).name() << endl;
}

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

//主函数
int main() {
	test01();
	test02();
	test03();
	system("pause");
	return 0;
}

总结:

  • 通过类模板创建的对象,可以有三种方式向函数中进行传参
  • 使用比较广泛的是第一种:指定传入的类型
3.5 类模板与继承

当类模板

碰到继承时,需要注意以下几点:

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

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

//class Son :public Base {}; //错误,必须要直到父类中的T类型,才能继承给子类
class Son :public Base<int> {

};

void test01() {
	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 test02() {
	Son2<int, char>S2;
}

//主函数
int main() {
	test01();
	test02();
	system("pause");
	return 0;
}
3.6 类模板成员函数类外实现

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

//类模板成员函数类外实现
template<class T1,class T2>
class Person {
public:
	T1 m_name;
	T2 m_age;

	void showPerson();
	Person(T1 name, T2 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 << "name: " << m_name << endl;
	cout << "age = " << m_age << endl;
}

void test01() {
	Person<string, int>p("张三", 20);
	p.showPerson();
}

//主函数
int main() {
	test01();
	system("pause");
	return 0;
3.7 类模板分文件编写

学习目标:

  • 掌握类模板成员函数分文件编写产生的问题以及解决方式

问题:

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

解决:

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

Person.hpp代码:

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

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

template<class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age) {
	this->m_age = age;
	this->m_name = name;
}

template<class T1, class T2>
void Person < T1, T2>::showPerson() {
	cout << "姓名:" << m_name << endl;
	cout << "年龄:" << m_age << endl;
}

源.cpp代码:

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

//第一种解决方式
//#include "Person.cpp"

//第二种解决方式
//将 .h 和 .cpp 中的内容写到一起,将后缀改为 .hpp
#include "Person.hpp"

void test01() {
	Person<string, int>p("Jerry", 18);
	p.showPerson();
}

//主函数
int main() {
	test01();
	system("pause");
	return 0;
}

总结:主流的解决方法是第二种,将类模板成员函数写到一起,并将后缀改为.hpp

3.8 类模板与友元

学习目标:

  • 掌握类模板配合友元函数的类内和类外实现

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

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

//通过全局函数 打印Person的信息

//提前让编译器直到Person类存在
template<class T1,class T2>
class Person;

//类外实现
template<class T1, class T2>
void printPerson2(Person<T1, T2>p) {
	cout << "类外实现-姓名:" << p.m_name << endl;
	cout << "类外实现-年龄:" << p.m_age << endl;
}

template<class T1,class T2>
class Person {
	//全局函数 类内实现
	friend void printPerson(Person<T1, T2>p) {
		cout << "类内实现-姓名:" << p.m_name << endl;
		cout << "类内实现-年龄:" << p.m_age << endl;
	}

	//全局函数 类外实现
	//加空模板参数列表
	//如果全局函数 是类外实现,需要让编译器提前知道这个函数的存在
	friend void printPerson2<>(Person<T1, T2>p);

private:
	T1 m_name;
	T2 m_age;
public:
	Person(T1 name, T2 age) {
		this->m_name = name;
		this->m_age = age;
	}
};

//1、全局函数在类内实现
void test01() {
	Person<string, int>p("Tom", 18);
	printPerson(p);
}

//2、全局函数类外实现
void test02() {
	Person<string, int>p("Jerry", 20);
	printPerson2(p);
}

//主函数
int main() {
	test01();
	test02();
	system("pause");
	return 0;
}

总结:建议全局函数做类内实现,用法简单,而且编译器可以直接识别

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三月江东

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值