模板类似于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();
}