(C++)函数模板与类模板基础知识

本文详细介绍了C++中的函数模板和类模板。从模板概念出发,探讨了函数模板的语法、注意事项、案例及与普通函数的区别。接着讲解了类模板的基本语法、与函数模板的区别、成员函数的创建时机、对象作为函数参数的方式以及在继承中的应用。最后讨论了类模板成员函数的类外实现和分文件编写的问题,以及类模板与友元的配合使用。

模板

1.1 模板的概念

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

1.2 函数模板

1.2.1 函数模板的语法

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

语法:

template <typename T>

函数声明或定义

解释:
template
—— 声明创建模板
tpyename
—— 表明其后面的符号是一种数据类型,可以用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)
{
	int temp = a;
	a = b;
	b = temp;
}
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);
	//1.自动类型推导
	mySwap(a,b);

	//2.显示指定类型
	mySwap<int>(a,b);
	cout << a << "   " << b <<endl;

	//double c = 10.0;
	//double d = 20.0;
	//swapDouble(c,d);
	//cout << a << "   " << b <<endl;
}


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

1.2.2 函数模板的注意事项


#include <iostream>
using namespace std;

//函数模板的注意事项

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

template<class T>	//typename 可以替换为 class
void mySwap(T &a, T &b)
{
	T temp = a;
	a = b;
	b = temp;
}
void test01()
{
	int a = 10;
	int b = 20;
	char c = 'c';
	
	mySwap(a,b);
	//mySwap(a,c);		错误,推导不出一致的T类型
	
	cout << a << endl;
	cout << b << endl;
}
//2.模板必须要确定出T的数据类型,才可以使用
template <class T>
void func()
{
	cout << "func is used" << endl;
}
void test02()
{
	func<int>(); //正确
	func();		 //错误
	//一定要确定数据类型,不然不能调用模板
}


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

1.2.3 函数模板案例

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


#include <iostream>
using namespace std;
//交换函数模板
template <class T>
void mySwap(T &a, T&b)
{
	int 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)
		{
			mySwap(arr[max],arr[i]);
			//交换max 与 i 
		}
	}
}
//输出数组模板
template <class T>
void printArray(T arr[], int len)
{
	for (int i = 0; i < len; i++)
	{
		cout << arr[i] << "  ";
	}
	cout << endl;
}
void test01()
{
	//测试char数组
	char charArr[] = "badcfe";
	int num = sizeof(charArr) / sizeof(char);
	mySort(charArr, num);
	printArray(charArr,num);
	cout << " ———————————————— " << endl;
}

void test02()
{
	//测试int数组
	int intArr[] = {8,3,57,23,4};
	int num = sizeof(intArr) / sizeof(int);
	mySort(intArr,num);
	printArray(intArr,num);
}

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

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

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

1.普通函数调用可以发生隐式类型转换
2.函数模板,用自动类型推导,不可以发生隐式转换
3.函数模板,用显示指定类型,可以发生隐式类型转换


#include <iostream>
using namespace std;
//普通函数
int myAdd01 (int a, int b)
{
	return a+b;
}
//模板函数
template <class T>
int myAdd02(T a, T b)
{
	return a+b;
}
void test01()
{
	int a = 10;
	int b = 20;
	char c = 'c';
	
	cout << myAdd01(a,c) << endl;
	//c = 99 , 使用普通函数 , 字符型隐式转换为整形

	cout << myAdd02(a,c) << endl;
	//c 是 char 类型 , 自动类型推导不会隐式转换

	cout << myAdd02<int>(a,c) << endl;
	//显示指定类型,会进行隐式转换
}

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

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

调用规则如下:
1.如果函数模板和普通函数都可以实现,优先调用普通函数
2.可以通过空模板参数列表来强制调用函数模板
3.函数模板也可以发生重载
4.如果函数模板可以产生更好的匹配,优先调用函数模板


#include <iostream>
using namespace std;
void myPrint(int a , int b)
{
	cout << " putong func is used" << endl;
}
template<class T>
void myPrint (T a, T b)
{
	cout << " muban1 func is used" << endl;
}
template<class T>
void myPrint (T a, T b, T c)
{
	cout << " muban2 func is used" << endl;
}

void test01()
{
	int a = 10;
	int b = 20;
	myPrint(a,b);
	//此时优先调用普通函数
	myPrint<>(a,b);
	//此时调用的是模板函数
	myPrint<>(a,b,100);
	//此时调用的是模板函数的重载
	char c = 'c';
	char d = 'd';
	myPrint(c,d);
	//此时调用的是模板函数
	
}

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

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

1.2.6 模板的局限性

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

};
template<> bool myCompare (Person &p1, Person &p2)
{
	if (p1.m_Age == p2.m_Age && p1.m_Name == p2.m_Name)
	{
		return true;
	}
	else
	{
		return false;
	}
	//重载后就可以比较 Person 类
}

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

	bool ret = myCompare(a,b);
	if (ret)
	{
		cout << " = " << endl;
	}
	else
	{
		cout << " != " << endl;
	}
}
void test02()
{
	Person p1("Tom", 10);
	Person p2("Tom", 10);

	bool ret = myCompare(p1,p2);

	if (ret)
	{
		cout << " = " << endl;
	}
	else
	{
		cout << " != " << endl;
	}
}
int main()
{
	test01();
	system("pause");
	return 0;
}

1.3 类模板

1.3.1 类模板的基本语法

语法:

template <typename T>

函数声明或定义

解释:
template
—— 声明创建模板
tpyename
—— 表明其后面的符号是一种数据类型,可以用class代替
T
—— 通用的数据类型,名称可以替换,通常为大写字母

#include <string>
#include <iostream>
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 << "  age :" << this ->m_Age << endl;
	}
};
void test01()
{
	Person<string,int> p1("xixixi",999);
	p1.showPerson();
}
int main()
{
	test01();
	system("pause");
	return 0;
}

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

类模板与函数模板区别主要有两点:
1.类模板没有自动类型推导的使用方式
2.类模板在参数列表中可以有默认参数


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

template<class NameType, class 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 << "  age :" << this ->m_Age << endl;
	}
};
void test01()
{
//	Person p("孙悟空",1000);
	//错误,无法自动推导类型
	
	Person<string, int> p("孙悟空",1000);
	//正确,手动显示了指定类型
	p.showPerson();
}
void test02()
{
	Person<string>p1("猪八戒",1000);
}
int main()
{
	test01();
	system("pause");
	return 0;
}

总结
1.类模板使用只能显示指定类型方式
2.类模板中的模板参数列表可以有默认参数

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

类模板中成员函数和普通类中成员函数创建时机是有区别的
1.普通类中的成员函数一开始就可以创建
2.类模板中的成员函数在调用时才创建

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

class Person1
{
public:
	void showPerson1()
	{
		cout << "This is Person1" << endl;
	}
};
class Person2
{
public:
	void showPerson2()
	{
		cout << "This is Person2" << endl;
	}
};
template<class T>
class MyClass
{
public:
	T obj;
	void func1()
	{
		obj.showPerson1();
	}
	void func2()
	{
		obj.showPerson2();
	}
};
void test01()
{
	
	//一开始不能运行是因为没有确定数据类型
	MyClass<Person1>m;
	//这一行确定了数据类型是Person1后,就可以调用func1
	
	m.func1();
	//可以运行
	
	//m.func2();
	//但不可调用func2
}
int main()
{
	test01();
	system("pause");
	return 0;
}

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

1.3.4 类模板对象做函数参数

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


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

template<class T1,class T2>
class Person
{
public:
	Person (T1 name, T2 age)
	{
		this ->m_Age  = age;
		this ->m_Name = name;
	}
	void showPerson()
	{
		cout << "Name :" << this ->m_Name << endl;
		cout << "Age  :" << this ->m_Age  << endl;
	}
	T1 m_Name;
	T2 m_Age;
};
//1.(最常用)
void printPerson1(Person<string,int>&p)
{
	p.showPerson();
}
void test01()
{
	Person<string,int>p("sunwukong",1000);
	printPerson1(p);
}
//2.
template<class T1, class T2>
void printPerson2(Person<T1,T2>&p)
{
	p.showPerson();
	cout << "T1's typename is " << typeid(T1).name()<<endl;
	cout << "T2's typename is " << typeid(T2).name()<<endl;
	//可以查看数据类型
}
void test02()
{
	Person<string,int>p("zhubajie", 90);
	printPerson2(p);
}
//3.
template<class T>
void printPerson3(T &p)
{
	p.showPerson();
	cout << "T's typename is " << typeid(T).name()<<endl;
	//可以查看T的数据类型
}
void test03()
{
	Person<string, int>p("tangseng",30);
	printPerson3(p);
}
int main()
{
	test03();
	system("pause");
	return 0;
}

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

1.3.5 类模板与继承

当类模板碰到继承时,需要注意以下几点
1.当子类继承的父类是一个类模板时,子类在声明的时候,要指定出父类中T的类型
2.如果不指定,编译器无法给子类分配内存
3.如果想灵活指定出父类中T的类型,子类也需变为类模板


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

template<class T>
class Base
{
	T m;
};
//class Son : public Base {}; 
//错误,必须要知道T的类型,才能继承给子类
class Son : public Base<int>
{

};
//灵活指定数据类型
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 test01()
{
	Son s1;
}
void test02()
{
	Son2<int , char>S2;
}
int main()
{
	test02();
	system("pause");
	return 0;
}

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

1.3.6 类模板成员函数类外实现


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

template<class T1, class T2>
class Person
{
public:
	Person (T1 name, T2 age);
	//{
	//	this ->m_Age  = age;
	//	this ->m_Name = name; 
	//}
	
	void showPerson();
	//{
	//	cout << " Name: " << this->m_Age  <<endl;
	//	cout << " Age : " << this->m_Name <<endl;
	//}
	T1 m_Name;
	T2 m_Age;
};
//构造函数和成员函数类外实现的语法
//构造函数
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 << " Name: " << this->m_Age  <<endl;
	cout << " Age : " << this->m_Name <<endl;
}
void test01()
{
	Person<string,int> p("Tom", 21);
	p.showPerson();
}

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

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

1.3.7 类模板分文件编写

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

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

主文件.cpp
#include <iostream>
#include <string>
using namespace std;

//第一种方法:直接包含源文件
#include "person.cpp"

//第二种方法:将.h和.cpp写在一起,将后缀名改为.hpp文件
#include "person.hpp"

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

int main()
{
	test01();
	system("pause");
	return 0;
}
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_Age  = age;
	this ->m_Name = name; 
}
//成员函数
template<class T1,class T2>
void Person<T1,T2>::showPerson()
{
	cout << " Name: " << this->m_Age  <<endl;
	cout << " Age : " << this->m_Name <<endl;
}
person.cpp
#include "person.h"
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 << " Name: " << this->m_Age  <<endl;
	cout << " Age : " << this->m_Name <<endl;
}

1.3.8 类模板与友元

学习目标:
掌握类模板配合友元函数的类内和类外实现

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

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

//要让函数提前知道类 Person 的存在
template<class T1,class T2>
class Person;
//要让编译器提前知道函数的存在
template<class T1, class T2>
void printPerson2(Person<T1,T2> p)
{
	cout << "printPerson2 is used" << endl;
}

template<class T1, class T2>
class Person
{
	//全局函数类内实现
	friend void printPerson(Person<T1,T2> p)
	{
		cout << "Name :" <<  p.m_Name << endl;
		cout << "Age :" <<  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;
};

void test01()
{
	Person<string,int>p("Tom",20);
	printPerson(p);
}
void test02()
{
	Person<string,int>p("Tom",20);
	printPerson2(p);
}
int main()
{
	test02();
	system("pause");
	return 0;
}

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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值