类模板
1、格式
1. 声明
template<typeclass T>
class AAA
/* 使用T表示某种类型,比如: */
private:
T obj;
public:
void test_func(T& t);
.....
;
2. 定义
template<typeclass T>
void AAA<T>::test_func(T& t) ....
2、使用
方法一:用到时再实例化:
AAA<int> a;
AAA<double> b;
方法二:事先实例化:
template AAA<int>;
再使用:
AAA<int> a;
3、定做(类似重载)
//1. 声明
template<>
class AAA<int>
......
public:
void test(void);
;
//2. 定义
void AAA<int>::test(void) ...
例子:
#include <iostream>
#include <string.h>
#include <unistd.h>
using namespace std;
template<typename T>
class AAA {
private:
T t;
public:
void test_func(const T &t);
void print(void);
};
template<typename T> void AAA<T>::test_func(const T &t)
{
this->t = t;
}
template<typename T>
void AAA<T>::print(void)
{
cout<<t<<endl;
}
/*定做*/
// template<>
// class AAA<int> {
// public:
// void test_func_int(const int & t)
// {
// cout<<t<<endl;
// }
// void print_int(void);
// };
// void AAA<int>::print_int(void)
// {
// cout<<"for test"<<endl;
// }
int main(int argc, char **argv)
{
AAA<int> a;
a.test_func(1.23);
a.print();
//a.test_func_int(1);
//a.print_int();
AAA<double> b;
b.test_func(1.23);
b.print();
return 0;
}