如何实现C++模板类头文件和实现文件分离,这个问题和编译器有关。
引用<<C++primer(第四版)>>里的观点:1)标准C++为编译模板代码定义了两种模型:“包含”模型和“分别编译”模型。2)所有编译器都支持“包含”模型,某些编译器支持“分别编译”模型。
第一种方法:按C++primer中的“包含”模型,在定义模板类的头文件中的末行用语句:#include "template_compile.cpp"
在类模板头文件template_compile.h中:
#ifndef _TEMPLATE_COMPILE_H
#define _TEMPLATE_COMPILE_H
template<class T> class base;
#include "template_compile.cpp"
#endif
在类模板的实现文件template_compile.cpp中:
template<class T>
class base
{
public:
base() {};
~base() {};
T add_base(T x,T y);
};
template<class T>
T base<T>::add_base(T x,T y)
{
return x+y;
}
在使用模板的测试文件use_template.cpp中:
#include<iostream>
using namespace std;
#include "template_compile.h"
void main()
{
base<int> bobj;
cout<<bobj.add_base(2,3)<<endl;
}
第二种方法: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"
在类模板的实现文件template_compile.cpp中:
#ifdef FUCK
template<class T>
T base<T>::add_base(T x,T y)
{
return x+y;
}
#endif
测试文件不变。
实验证明:在VC9.0中,这种方法可以实现类模板头文件和实现文件的分离
方法三:
在类模板头文件template_compile.h中:
template<class T>
class base
{
public:
base() {};
~base() {};
T add_base(T x,T y);
};
在类模板的实现文件template_compile.cpp中:
#include "template_compile.h"
template<class T>
T base<T>::add_base(T x,T y)
{
return x+y;
}
在使用模板的测试文件use_template.cpp中:使用#include "template_compile.cpp"
#include<iostream>
#include "template_compile.cpp"
using namespace std;
void main()
{
base<int> bobj;
cout<<bobj.add_base(2,3)<<endl;
}
实验证明:在VC9.0中,这种方法可以实现类模板头文件和实现文件的分离。
另外实验证明:VC9.0不支持“分别编译”模型。
转自:http://blog.youkuaiyun.com/Microsues/article/details/6078385
ps:方法1与原文不同,
参考:http://kymcuc.blog.163.com/blog/static/201942114201231184541184/