模板(C++)(未完待续)

版权声明:原创文章,转载请声名。 https://blog.csdn.net/qq_40707451/article/details/85330923

为了提高程序的可重用性,C++中引入了模板这一概念。

举例来说,为了实现一个交换函数,因为数据类型的关系,可能你需要实现好几种只是参数类型有差异的相同的函数,这大大降低了我们的工作效率;但通过使用模板我们可以实现一个万能的交换函数。

函数模板形式如下:

template <class 类型参数1, class类型参数2, ...>
返回值类型  模板名(形参表)
{
    函数体
}

其中的 class 关键字也可以用 typename 关键字替换,例如:

template <typename 类型参数1, typename 类型参数2, ...>

模板重载

在有多个函数和函数模板名字相同的情况下,一条函数调用语句到底应该被匹配成对哪个函数或哪个模板的调用呢? C++编译器遵循以下先后顺序:

  1. 先找参数完全匹配的普通函数(非由模板实例化得到的函数)。
  2. 再找参数完全匹配的模板函数。
  3. 再找实参经过自动类型转换后能够匹配的普通函数。
  4. 如果上面的都找不到,则报错。

代码说明

#include<iostream>
using namespace std;
template<class T>
void Swap(T& a, T& b)
{
	T temp = a;
	a = b;
	b = temp;
}
//编译器由模板自动生成函数的过程叫做模板的实例化,生成的函数叫做模板函数
//通过 模板名<类型名1,类型名2,...>(显式定义)这种方式告诉编译器应该如何实例化
//模板函数template<class T>
template<class T>
T sum(int a)
{
	return a + 1;
}
//模板函数可以不只有一个参数
template<class T1,class T2>
T1 Print(T1 arg1, T2 arg2)
{
	cout << arg1 << " " << arg2 << endl;
	return arg1;
}
//模板重载
void test(int num1,int num2)
{
	cout << "noraml:"<< endl;
}

template<class T>
void test(T num1,T num2)
{
	cout << "templete:" << endl;
}

template<class T1,class T2>
void test(T1 num1,T2 num2)
{
	cout << "adjust templete:"  << endl;
}


int main()
{
	int a = 1, b = 2;
	Swap(a, b);
	cout << a << " " << b << endl;
	double c = 1.2, d = 1.0;
	Swap(c, d);
	cout << c << " " << d << endl;
	char e = 'E', f = 'F';
	Swap(e, f);
	cout << e << " " << f << endl;
	

	cout << sum<double>(4) / 2 << endl;

	int arg1 = 2;
	char*arg2 = "HELLO";

	test(1, 2);
	test(1.2, 2);

	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40707451/article/details/85330923
今日推荐