如何实现C++模板类头文件和实现文件分离,这个问题和编译器有关。
第一种方法:bruceteen提出的:使用define
在类模板头文件template_compile.h中:
- template<class T>
- class base
- {
- public:
- base() {};
- ~base() {};
- T add_base(T x,T y);
- };
- #define FUCK
- #include "template_compile.cpp"
- #ifdef FUCK
- template<class T>
- T base<T>::add_base(T x,T y)
- {
- return x+y;
- }
- #endif
方法二:在类模板头文件template_compile.h中:
- template<class T>
- class base
- {
- public:
- base() {};
- ~base() {};
- T add_base(T x,T y);
- };
- #include "template_compile.h"
- template<class T>
- T base<T>::add_base(T x,T y)
- {
- return x+y;
- }
- #include<iostream>
- #include "template_compile.cpp"
- using namespace std;
- void main()
- {
- base<int> bobj;
- cout<<bobj.add_base(2,3)<<endl;
- }
第三种方法:在类模板头文件template_compile.h中: (经验证,好像不行)
- template<class T>
- class base
- {
- public:
- base() {};
- ~base() {};
- T add_base(T x,T y);
- };
- #include "template_compile.cpp"
- template<class T>
- T base<T>::add_base(T x,T y)
- {
- return x+y;
- }
- #include<iostream>
- #include "template_compile.h"
- using namespace std;
- void main()
- {
- base<int> bobj;
- cout<<bobj.add_base(2,3)<<endl;
- }
C++模板分离编译

本文介绍了三种实现C++模板类头文件与实现文件分离的方法,包括使用预处理宏、直接包含实现文件以及在头文件中声明并在单独的CPP文件中定义等方案。
2564

被折叠的 条评论
为什么被折叠?



