假设我有2个头文件,1个.ipp扩展文件和一个main.cpp文件:
第一个头文件(如Java中的接口):
template<class T>
class myClass1{
public:
virtual int size() = 0;
};
第二个头文件:
#include "myClass1.h"
template<class T>
class myClass2 : public myClass1<T>
public:
{
virtual int size();
private:
int numItems;
};
#include "myClass2.ipp"
然后是我的myClass2.ipp文件:
template <class T>
int myClass2<T>::size()
{
return numItems;
}
最后一个是我的主要成员:
#include "myclass2.h"
void tester()
{
myClass2<int> ForTesting;
if(ForTesting.size() == 0)
{
//......
}
else
{
//.....
}
}
int main(){
tester();
return 0;
}
myClass1,myClass2和myClass2.ipp属于头文件。源文件中的main.cpp。 使用这种方式实现程序而不是仅仅使用它有什么好处 .h和.cpp文件?什么是.ipp扩展名的文件? .ipp和.cpp之间的区别?
答案 0 :(得分:16)
<强> TR; DR 强>
.cpp
文件是一个单独的翻译单元,标题中包含.ipp
,并进入包含该标题的所有翻译单元。
<强>解释强>
在模板之前,您将方法的声明放在头文件中,并且实现转到.cpp
文件。这些文件是作为自己的编译单元单独编译的。
使用模板,几乎不再需要在标题中定义所有模板方法。为了至少在逻辑层面上将它们分开,有些人将声明放在标题中,但将模板方法的所有实现移动到.ipp
文件(i
为“内联”)并包含{{1}标题末尾的文件。
答案 1 :(得分:3)
我在使用.ipp文件时看到的另一个优点是,您可以选择是否包括模板的实现部分。这样,您可以通过实例化.cpp文件中某些参数的模板来减少编译时间,以便对它们进行预编译,同时保留实例化其他参数的模板的可能性。示例:
// x.hpp
template <typename T>
struct X
{
int f();
}
// x.ipp
#include "x.hpp"
template <typename T>
int X::f()
{
return 42;
}
// x.cpp
#include "x.ipp"
// Explicit instantiation of X<> for int and double;
// the code for X<int> and X<double> will be generated here.
template class X<int>;
template class x<double>;
// foo.cpp
// Compilation time is reduced because
// the definitions of X member functions are not parsed.
#include "x.hpp"
void foo()
{
X<int> x;
x.f();
}
// bar.cpp
// Here we need to include the .ipp file because we need to instantiate
// X<> for a type which is not explicitly instantiated in x.cpp.
#include "x.ipp"
#include <string>
void bar()
{
X<std::string> x;
x.f();
}