函数模版和类模板的使用

版权声明:转载请注明出处。作者:两仪织,博客地址:http://blog.csdn.net/u013894427 https://blog.csdn.net/u013894427/article/details/83350402

template

template用于重载(overriding),目的是让形参类型不同的函数可以共用一个类名或者函数名。

  1. 最简单的使用,对一个函数进行重载,参数是可变的
    原型:
template <class identifier> function_declaration;

NOTICE:

  T也可以作为函数的返回值进行设置,并不一定是参数。
例子:

#include <iostream>
using namespace std;

template <typename T>
void show(T t)
{
	cout << "the parm is " << t << endl;
}

int main()
{
	show(123);
	show("abc");
	return 1;
}
  1. 和类一起使用,对参数进行限制
    原型:

template <typename identifier> function_declaration;

例子

#include <iostream>
using namespace std;

template <class T> class TemC
{
	public:
	    //并不是每一个函数都需要设置动态类型
		void show(T t);
};

template <typename T> void TemC<T>::show(T t)
{
	cout << "the parm is " << t << endl;
}

int main()
{
    //设置T为int之后,函数就只能接受int类型的参数
	TemC<int> tempC;
	tempC.show(123);
	//tempC.show("abc");
	return 1;
}

猜你喜欢

转载自blog.csdn.net/u013894427/article/details/83350402