C++笔记 day33 函数模板 类模板

161 阅读7分钟

函数模板

image.png

泛型编程 – 模板技术 特点:类型参数化

template< typename T >  
告诉编译器后面紧跟着的函数或者类中出现T,不要报错,T是一个通用的数据类型

实现通用两个数进行交换函数

使用

  1. 自动类型推导   必须要推导出一致的T才可以使用

  2. 显示指定类型   mySwap(a,b);

示例

  
//利用模板实现通用交换函数
template<typename T> //T代表一个通用的数据类型,告诉编译器如果下面紧跟着的函数或者类中出现T不要报错
void mySwap(T& a,T& b) 
{
	T temp = a;
	a = b;
	b = temp;
}
//模板不能单独使用,必须指定出T才可以使用
template<typename T>
void mySwap2() 
{
	
}
//对于没有传参的函数,需要在调用的时候显示指定类型调用
//	mySwap2<double>();


void  test01() 
{
	double a = 1.1;
	double b = 1.2;
	char c = 'c';
	//模板2种调用方式
	//1. 自动类型推导,必须推导出一致的T数据类型才可以正常使用模板
	//mySwap(a, b); 推导不出一致的T,因此无法调用
	mySwap(a, b);
	// 2. 显示指定类型
	mySwap<double>(a, b);
	cout << a << endl;
	cout << b << endl;
	mySwap2<double>();//必须告诉编译器模板类型才可以调用
}  

实现对char和 int类型数组进行排序

利用模板技术 实现对char和int类型数组通用排序函数

示例

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;

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

//需求,通过一个通用排序函数,实现对char和int数组的排序,排序顺序,从大到小,算法 选择排序
template<class T> //typename 和 class 一样
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;
			}
		}
		//判断 算出的max和开始认定的i是否一致,如果不同交换数据
		if (i != max) 
		{
			mySwap(arr[i], arr[max]);
		}
	}
}

template<class T >
void printArray(T arr[], int len) 
{
	for (int i = 0; i < len; i++)
	{
		cout << arr[i] << endl;
	}
}

void test01() 
{
	char charArray[] = "helloworld";
	int len = strlen(charArray);
	mySort(charArray, len);

	printArray(charArray,len);
	int intArray[] = {5,7,4,1,2,3};
	int len1 = sizeof(intArray) / sizeof(int);
	mySort(intArray, len1);
	printArray(intArray, len1);

}

int main()
{
	test01();


	system("pause");
	return EXIT_SUCCESS;
}   

函数模板和普通函数的区别以及调用规则

区别

如果使用自动类型推导,是不可以发生隐式类型转换的

普通函数 可以发生隐式类型转换

调用规则

1. 如果函数模板和普通函数都可以调用,那么优先调用普通函数

2. 如果想强制调用函数模板,可以使用空模板参数列表

    myPrint<>(a, b);

3. 函数模板也可以发生函数重载

4. 如果函数模板能产生更好的匹配,那么优先使用函数模板

示例

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;



//1. 函数模板和普通函数的区别
template <class T>
int myAdd(T a, T b) 
{
	return a + b;
}

int myAdd2(int a, int b) 
{
	return a + b;
}

void test01() 
{
	int a = 10;
	int b = 20;
	char c = 'c';
	//myAdd(a, c);//如果使用自动类型推导,是不可以发生隐式类型转换的

	myAdd2(a, c);//普通函数,可以发生隐式类型转换
}

//函数模板和普通函数的调用规则
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 myPrint(int a, int b) 
{
	cout << "普通函数调用" << endl;
}

void test02() 
{
	//1. 如果函数模板和普通函数都可以调用,那么优先调用普通函数
	int a = 10;
	int b = 20;
	myPrint(a, b);

	//2. 如果想强制调用函数模板,可以使用空模板参数列表
	myPrint<>(a, b);

	//3. 函数模板也可以发生函数重载
	myPrint(a, b, 10);

	//4. 如果函数模板能产生更好的匹配,那么优先调用函数模板
	char c = 'c';
	char d = 'd';
	myPrint(c, d);
}

int main(void)
{
	test02();

	system("pause");
	return EXIT_SUCCESS;
}
   

模板的实现机制

  1. 编译器并不是把函数模板处理成能够处理任何类型的函数
  2. 函数模板通过具体类型产生不同的函数 ---  通过函数模板产生的函数 称为模板函数
  3. 编译器会对函数模板进行两次编译,在声明的地方对模板代码本身进行编译,在调用的地方对参数替换后的代码进行编译。

模板局限性

image.png

模板并不是真实的通用,对于自定义数据类型,可以使用具体化技术,实现对自定义数据类型特殊使用

 **template** **<>** bool myCompare(**Person** &a, **Person** &b)

示例:模板局限性

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;

class Person 
{
public:
	Person(string name,int age)
	{
		this->m_Name = name;
		this->m_Age = age;
	}
	string m_Name;
	int m_Age;
};

// 显示两个变量 对比 函数
template <class T>
bool myCompare(T& a, T& b) 
{
	if (a == b) 
	{
		return true;
	}
	return false;
}

//利用具体化技术 实现对自定义数据类型 提供特殊模板
template<> bool myCompare(Person& a, Person& b) 
{
	if (a.m_Name == b.m_Name && a.m_Age == b.m_Age) 
	{
		return true;
	}
	return false;
}
void test01() 
{
	int a = 10;
	int b = 10;

	bool ret = myCompare(a, b);

	if (ret) 
	{
		cout << "a = b" << endl;
	}
	else
	{
		cout << "a != b" << endl;
	}

	Person p1("TOM", 19);
	Person p2("TOM", 20);


	ret = myCompare(p1, p2);

	if (ret)
	{
		cout << "p1 = p2" << endl;
	}
	else
	{
		cout << "p1 != p2" << endl;
	}
}
int main()
{
	test01();


	system("pause");
	return EXIT_SUCCESS;
}

类模板

类模板和函数模板区别:

1、类模板不可以使用自动类型推导,只能用显示指定类型

2、类模板中 可以有默认参数

示例

#define _CRT_SECURE_NO_WARNINGS
#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 << "姓名:" << this->m_Name << " 年龄" << this->m_Age << endl;
	}
	NAMETYPE m_Name;
	AGETYPE m_Age;
};

void test01() 
{
	// 1. 自动类型推导  类模板不可以使用 自动类型推导
	//Person p1("孙悟空", 100); 报错
	//2.  显示指定类型
	Person<string, int> p1("孙悟空", 100);
	Person<string>p2("猪八戒", 200);//类模板中可以有默认参数,这里利用了默认参数
	p1.showPerson();
	p2.showPerson();
}

int main()
{

	test01();

	system("pause");
	return EXIT_SUCCESS;
}

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

类模板中的成员函数  并不是一开始创建的,而是在运行阶段确定出T的数据类型才去创建

示例

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;

//类模板中的成员函数不是在一开始就创建好的,而是在运行阶段,确定好数据类型了,才会创建
class Person1 
{
public:
	void showPerson1() 
	{
		cout << "Person1 show 调用" << endl;
	}
};

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

template<class T>
class MyClass 
{
public:
	void func1() 
	{
		obj.showPerson1();
	}
	void func2() 
	{
		obj.showPerson2();
	}
	T obj;
};
void test01() 
{
	MyClass<Person1>p1;
	p1.func1();

}
int main()
{
	test01();


	system("pause");
	return EXIT_SUCCESS;
}

类模板做函数参数

1、指定传入类型

void doWork(Person <string, int>&p)

2、参数模板化

template<class T1, class T2>

void doWork2(Person <T1, T2>&p)

3、整个类 模板化

template<class T>

void doWork3( T &p)

查看T数据类型

typeid(T).name()

类模板碰到继承的问题以及解决

必须要指定出父类中的T数据类型,才能给子类分配内存

 template<class T1 ,class T2>

class Son2 :public Base2<T2>

示例

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;

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

//必须要制定出父类中T数据类型,才能给子类分配内存
class Son :public Base<int>
{

};

template<class T>
class Base2
{
public:

	T m_A;
};

template<class T1,class T2>
class Son2 :public Base2<T2> 
{
public:
	
	Son2()
	{
		cout << typeid(T1).name() << endl;
		cout << typeid(T2).name() << endl;
	}T1 m_B;
};

void test01() 
{
	Son2<int, double> s;
}

int main()
{

	test01();

	system("pause");
	return EXIT_SUCCESS;
}

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

template<class T1,class T2>
void Person<T1, T2>::showPerson()

类模板的分文件编写问题以及解决

类模板中的成员函数,不会一开始创建,因此导致分文件编写时连接不到函数的实现,出现无法解析的外部命令错误

  1. 解决方式1:

    直接包含.cpp文件 (不推荐)

  2. 解决方式2:

    将类声明和实现写到同一个文件中,将文件的后缀名改为 .hpp 即可

示例 .hpp文件

#pragma once
#define _CRT_SECURE_NO_WARNINGS
#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;
}
  

示例:主函数

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
//#include "Person.cpp" //这里不能包含.h 包含.cpp就可以
//因为类模板中的成员函数一开始不会创建,因此如果只是include .h 看不到
//但是不建议include包含源文件,也不建议对类模板的成员函数进行分文件编写
//因此可以把类模板及其类外成员函数实现放到一个文件里,特别命名为.hpp
#include "Person.hpp"
#include<string>

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

int main()
{
	test01();


	system("pause");
	return EXIT_SUCCESS;
}

类模板碰到友元的问题以及解决

  1. 友元类内实现

     friend void printPerson(Person<T1, T2> &p)
    
  2. 友元类外实现

    声明:

     friend void printPerson2<>(Person<T1, T2> &p);
    

    实现:

     template<class T1,class T2>
    
     void printPerson2(Person<T1, T2> &p){ 。。。}
    
     template<class T1,class T2>
    
     class Person;
    
    
    
     template<class T1,class T2>
    
     void printPerson2(Person<T1, T2> &p);
    

示例

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

template<class T1, class T2>
class Person;

template<class T1, class T2>
void printPerson2(Person<T1, T2>& p);

template<class T1, class T2>
void printPerson3(Person<T1, T2>& p) 
{
	cout << "类外实现:姓名:" << p.m_Name << " 年龄: " << p.m_Age << endl;
}

template <class T1, class T2>
class Person
{
public:
	//1. 友元函数 类内实现
	friend void printPerson(Person<T1, T2>& p) 
	{
		cout << "姓名:" << p.m_Name<< " 年龄: " << p.m_Age << endl;
	}

	//2. 友元函数 类外实现
	friend void printPerson2<>(Person<T1, T2>& p);
	//要在函数名后加<>表明是模板实现,并且还要提前在类前声明相关  类模板 和 函数模板

	//3. 友元函数,类外实现,简化,可以在开头把函数模板声明和实现放到一起
	friend void printPerson3<>(Person<T1, T2>& p);
	Person(T1 name, T2 age) 
	{
		this->m_Name = name;
		this->m_Age = age;
	}

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", 18);
	//printPerson(p);
	printPerson2(p);
	printPerson3(p);
}

int main()
{

	test01();

	system("pause");
	return EXIT_SUCCESS;
}

类模板应用 – 数组类封装

将类写到 myArray.hpp中

属性:

T  * pAddress; 指向堆区数组指针

int m_Capacity 数组容量

int m_Size ;数组大小

行为

myArray(int capacity)

myArray(const MyArray & arr)

operator=

operator[]

~myArray()

getCapacity

getSize

pushback

示例:hpp文件

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

template<class T>
class MyArray 
{
public:
	MyArray() {}
	//有参构造
	MyArray(int capacity) 
	{
		this->m_Capacity = capacity;
		this->m_Size = 0;
		this->pAddress = new T[this->m_Capacity];
	}
	//拷贝构造
	MyArray(const MyArray & arr)
	{
		this->m_Capacity = arr.m_Capacity;
		this->m_Size = arr.m_Size;
		this->pAddress = new T[this->m_Capacity];
		for (int i = 0; i < arr.m_Size; i++)
		{
			this->pAddress[i] = arr.pAddress[i];
		}
	}

	//重载 =
	MyArray& operator=(const MyArray &arr) 
	{
		if (this->pAddress) 
		{
			delete[] this->pAddress;
			this->pAddress = NULL;
		}
		this->m_Capacity = arr.m_Capacity;
		this->m_Size = arr.m_Size;
		this->pAddress = new T[this->m_Capacity];
		for (int  i = 0; i < arr.m_Size; i++)
		{
			this->pAddress[i] = arr.pAddress[i];
		}
		return *this;
	}

	//重载[]
	T& operator[](int index) 
	{
		return this->pAddress[index];
	}
	// 尾插法
	void pushBack(const T& val) 
	{
		if (this->m_Capacity == this->m_Size) 
		{
			return;
		}
		this->pAddress[this->m_Size] = val;
		this->m_Size++;
	}
	//获取数组容量
	int getCapacity() 
	{
		return this->m_Capacity;
	}
	//获取数组大小
	int getSize() 
	{
		return this->m_Size;
	}
	
	//析构
	~MyArray() 
	{
		if (this->pAddress)
		{
			delete[] this->pAddress;
			this->pAddress = NULL;
		}
	}
private:
	T* pAddress;//指向堆区真实数组指针
	int m_Capacity;//数组容量
	int m_Size;//数组大小
};

示例:主函数

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

class Person 
{
public:
	Person() {} //在堆区new一个Person必须要有默认构造函数
	Person(string name, int age) 
	{
		this->m_Name = name;
		this->m_Age = age;
	}
	string m_Name;
	int m_Age;
};

void myPrintInt(MyArray<int>&myIntArr) 
{
	for (size_t i = 0; i < myIntArr.getSize(); i++)
	{
		cout << myIntArr[i] << endl;
	}
}

void test01() 
{
	MyArray<int>myIntArr(100);
	for (size_t i = 0; i < 10; i++)
	{
		myIntArr.pushBack(i + 1000);
	}myPrintInt(myIntArr);
}

void myPrintPerson(MyArray<Person>& myPersonArr) 
{
	for (size_t i = 0; i < myPersonArr.getSize(); i++)
	{
		cout << "姓名:" << myPersonArr[i].m_Name << " 年龄:" << myPersonArr[i].m_Age << endl;
	}
}

void test02() 
{
	MyArray<Person> myPersonArr(100);
	Person p1("Andy",100);
	Person p2("Beny", 200);
	Person p3("Cany", 300);
	Person p4("Dery", 400);
	Person p5("Elly", 500);

	myPersonArr.pushBack(p1);
	myPersonArr.pushBack(p2);
	myPersonArr.pushBack(p3);
	myPersonArr.pushBack(p4);
	myPersonArr.pushBack(p5);

	myPrintPerson(myPersonArr);

	cout << "数组容量" << myPersonArr.getCapacity() << endl;
	cout << "数组大小" << myPersonArr.getSize() << endl;

}

int main()
{
	test02();


	system("pause");
	return EXIT_SUCCESS;
}