C++模板

C++模板分为函数模板和类模板。

函数模板

#include <iostream>

using namespace std;

/*
函数模板:

template <class(也可以用typename) T>
返回类型 函数名( 形参表 )
{
	//函数定义体 
}

类模板:

template <class(也可以用typename) T>
class 类名
{
	//类定义
}
*/

template <typename type1,typename type2>
void template_test(type1 param1,type2 param2)
{
	cout << "param1: ";
	cout << param1;
	cout << endl;

	cout << "param2: ";
	cout << param2;
	cout << endl;
	cout << "--------------------" << endl;
}

int main(char *argv,int argc)
{
	template_test(10,20);
	template_test("hello","world");
	template_test(30,"Hello world");

	cout<< endl << "Test over!" << endl;
	return 0;
}
运行以上代码,结果如下:

param1: 10
param2: 20
--------------------
param1: hello
param2: world
--------------------
param1: 30
param2: Hello world
--------------------

Test over!


类模板

#include <iostream>

using namespace std;

/*
函数模板:

template <class(也可以用typename) T>
返回类型 函数名( 形参表 )
{
	//函数定义体 
}

类模板:

template <class(也可以用typename) T>
class 类名
{
	//类定义
}
*/

template <typename type1,typename type2>
class TemplateTest
{
public:
	TemplateTest(type1 a,type2 b){
		param1 = a;
		param2 = b;
	}
	~TemplateTest(){}

public:
	void printParams(){
		cout << "param1: ";
		cout << param1;
		cout << endl;

		cout << "param2: ";
		cout << param2;
		cout << endl;
		cout << "--------------------" << endl;		
	}
private:
	type1 param1;
	type2 param2;
};



int main(char *argv,int argc)
{
	//定义类对象的时候,要指定参数类型
	TemplateTest<int,char*> templateTest(10,"hello world");
	templateTest.printParams();

	cout<< endl << "Test over!" << endl;
	return 0;
}
运行上述代码,结果如下:

param1: 10
param2: hello world
--------------------

Test over!

非类型模版参数(常量参数)

#include <iostream>

using namespace std;

/*
非类型模版参数(常量参数)

定义一个确定类型的常量作为模板参数,
这个常量不作为函数参数,
因此在实际调用函数时,
传递的函数参数中不包括这个参数。

*/

template <int SIZE,typename type>
void template_test(type param)
{
	char array[SIZE];
	cout << "Array size is " << sizeof(array) << endl;
	cout << "SIZE = " << SIZE << endl;
	cout << "param = " << param << endl;
	cout << "--------------------" << endl;
}


int main(char *argv,int argc)
{
	//传递的函数参数中不包括SIZE这个参数
	template_test<55>("hello world");

	cout<< endl << "Test over!" << endl;
	return 0;
}
执行上述代码,得到的结果如下:

Array size is 55
SIZE = 55
param = hello world
--------------------

Test over!






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值