C++模板

模板类似于Java中的泛型。

编译器会为模板的每种类型生成对应的类,如下例中会生成int_Stact和string_Stack两个类。

#include <iostream>

using namespace std;

#define LOGE(e) cout << #e << "=" << e << endl;

//类模板
template<class T, size_t N = 100> class Stack
{
	T data[N];
	size_t cur_pos;
public:
	Stack() {
		cur_pos = 0;
	}

	void push(const T& t)
	{
		data[cur_pos++] = t;
	}

	T pop()
	{
		return data[--cur_pos];
	}
};

//函数模板
template<typename T> void copy_t(T* t1, size_t size, T* t2)
{
	for (size_t i=0; i<size; i++) {*t2++ = *t1++;}
}

void template_class_test()
{
	Stack<int> int_stack;
	int_stack.push(15);
	int_stack.push(23);
	LOGE(int_stack.pop());
	LOGE(int_stack.pop());

	Stack<string> str_stack;
	str_stack.push("Davee");
	str_stack.push("Phil");
	LOGE(str_stack.pop().c_str());
	LOGE(str_stack.pop().c_str());

/* output
int_stack.pop()=23
int_stack.pop()=15
str_stack.pop().c_str()=Phil
str_stack.pop().c_str()=Davee
*/
}

void template_function_test()
{
	int i1[] = {3,15,8};
	int i2[3];
	copy_t<int>(i1, 3, i2);
	LOGE(i2[0]);
	LOGE(i2[1]);
	LOGE(i2[2]);

	string s1[] = {"Davee", "Phil"};
	string s2[2];
	copy_t<string>(s1, 2, s2);
	LOGE(s2[0].c_str());
	LOGE(s2[1].c_str());
/* output
i2[0]=3
i2[1]=15
i2[2]=8
s2[0].c_str()=Davee
s2[1].c_str()=Phil
*/
}

void main()
{
	template_class_test();

	template_function_test();

getchar();
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值