godson

模板的定义与实现分离

模板定义和实现分离:

 1 #ifndef _TEST_H_
 2 #define _TEST_H_
 3 
 4 template <class T>
 5 class test {
 6 public:
 7     test(T v1, T v2);
 8     test();
 9 
10     int compare() const;
11 private:
12     T _v1;
13     T _v2;
14 };
15 //此处包含test.cpp实现分离
16 #include "test.cpp"
17 
18 #endif
19 

 1 template<class T>
 2 test<T>::test() : _v1(0),_v2(1) {
 3 
 4 }
 5 
 6 template<class T>
 7 test<T>::test(T v1, T v2): _v1(v1),_v2(v2) {
 8 
 9 }
10 
11 template<class T>
12 int test<T>::compare() const {
13     return _v1>_v2?1:-1;
14 }
15 

 1 #include <iostream>
 2 #include "test.h"
 3 
 4 using namespace std;
 5 
 6 int main() {
 7     cout << "输入两个数:" << endl;
 8     int value1,value2;
 9     cin >> value1 >> value2;
10     test<int> t(value1,value2);
11     cout << t.compare() <<endl;
12 
13     return 1;
14 }
15 
16 
g++ main.cpp -o main编译通过
这个可以作用于函数模板和类模板

C++标准有一个export关键字用来实现模板的定义和实现分离的,只是到现在没有找到支持这个关键字的编译器,有点扯淡。

posted on 2009-10-26 13:48 伴我闯天涯 阅读(301) 评论(0)  编辑 收藏 引用

My Links

Blog Stats

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜