C++学习(十七)—模板(一)

函数模板基本用法

函数模板
template 告诉编译器T是万能数据类型,下面紧跟着的函数或者类中出现T类型,不要报错
调用模板函数
自动类型推导 必须让编译器推导出一致T类型才可以使用模板
显式指定类型 显式的告诉编译器T的类型
模板必须要指出T的类型,才可以使用

#include<iostream>

using namespace std;


void myswapInt(int &a,int &b)
{
	int temp = a;
	a = b;
	b = temp;
}


//  利用模板实现通用交换函数
template<typename T>//T是一个通用类型,告诉编译器后面紧跟着的函数或者类中出现了T,不要报错
void mySwap(T&a, T&b)
{
	T temp = a;
	a = b;
	b = temp;
}

template<typename T>
void MySwap2()
{
	;
}



void test01()
{
	int a = 10;
	int b = 20;
	//1、自动类型推导  必须让编译器推导出一致的T,才能使用模板
	mySwap(a, b);
	
	//2、显示指定类型 
	mySwap<int>(a, b);  //  显示指定类型可以进行隐式类型转换  如果转不成功,那么也不可以使用模板

	cout << a << endl;
	cout << b << endl;


	double c = 3.14;
	double d = 1.23;
	mySwap(c, d);
	cout << c << endl;
	cout << d << endl;


	MySwap2<double>();//	模板必须要指出T的类型,才可以使用
}

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

对数组排序

#include<iostream>

using namespace std;

template<typename T>
void Myswap(T &x, T &y)
{
	T temp = x;
	x = y;
	y = temp;
}



template<typename T>
void Mysort(T arr[], int len)
{
	int i, j;
	for (i = 0; i < len - 1; i++)
	{
		for (j = 0; j < len - i - 1; j++)
		{
			if (arr[j] > arr[j + 1])
			{
				Myswap(arr[j], arr[j + 1]);
			}
		}
	}
}

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




void test01()
{
	int a[] = { 22,13,189,45,8 };
	int len = sizeof(a) / sizeof(a[0]);
	Mysort(a, len);
	Myprint(a, len);

	char b[] = "helloworld";
	len = sizeof(b) / sizeof(b[0]);
	Mysort(b, len);
	Myprint(b, len);
}



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

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

#include<iostream>

using namespace std;

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

template<class T>
T MyPlus2(T a, T b)
{
	return a + b;
}

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

	char c = 'c';
	cout << MyPlus(a, c) << endl;

	cout << MyPlus2<int>(a, c) << 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 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()
{
	test02();
	system("pause");
	return 0;
}
发布了31 篇原创文章 · 获赞 8 · 访问量 3657

猜你喜欢

转载自blog.csdn.net/qq_42689353/article/details/104782125