假设我有2个头文件,1个.ipp扩展文件和一个main.cpp文件:
第一个头文件(如Java中的接口):
template<class T>
class myClass1{
public:
virtual int size() = 0;
};
Run Code Online (Sandbox Code Playgroud)
第二个头文件:
#include "myClass1.h"
template<class T>
class myClass2 : public myClass1<T>
public:
{
virtual int size();
private:
int numItems;
};
#include "myClass2.ipp"
Run Code Online (Sandbox Code Playgroud)
然后是我的myClass2.ipp文件:
template <class T>
int myClass2<T>::size()
{
return numItems;
}
Run Code Online (Sandbox Code Playgroud)
最后一个是我的主要:
#include "myclass2.h"
void tester()
{
myClass2<int> ForTesting;
if(ForTesting.size() == 0)
{
//......
}
else
{
//.....
}
}
int main(){
tester();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
myClass1,myClass2和myClass2.ipp属于头文件.源文件中的main.cpp.使用这种方式实现程序而不是仅使用.h和.cpp文件有什么好处?什么是.ipp扩展名的文件?.ipp和.cpp之间的区别?
Dan*_*rey 19
TR; DR
该.cpp文件是一个单独的翻译单元,.ipp它包含在标题中,并进入包括该标题在内的所有翻译单元.
说明
在模板之前,您将方法的声明放在头文件中,并将实现转到.cpp文件中.这些文件是作为自己的编译单元单独编译的.
使用模板,这不再可能,几乎所有模板方法都需要在标头中定义.为了至少在逻辑层面上将它们分开,有些人将声明放在标题中,但将模板方法的所有实现移动到.ipp文件(i用于"内联")并将.ipp文件包含在标题的末尾.
小智 7
我发现使用 .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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10665 次 |
| 最近记录: |