【发布时间】:2012-10-06 17:54:25
【问题描述】:
对于基于模板的类(STL 和 boost)不使用源文件并将实现也放入标题中似乎是一种常见的约定。我认为与头文件和源文件中的声明和实现之间的经典分离相比,这将大大增加编译包含头文件的源文件所需的时间。 The reason why this is done is probably due to the fact that you would have to tell the compiler in the source file which templates to use, which will probably result in a bloated .a file.
假设随着库的增长,链接器也需要更多时间,就编译包含库头文件的源文件所需的时间而言,哪种方法更快?
1。不使用 .cpp 文件并将整个类(包括实现)放入标题中
//foo.hpp
template <class T>
class Foo
{
public:
Foo(){};
T bar()
{
T* t = NULL;
//do stuff
return *t;
}
};
或
2。在库本身的源文件中为各种类型显式编译模板
//foo.h
template <class T>
class Foo
{
public:
Foo(){};
T bar();
};
//foo.cpp
template <class T>
T Foo<T>::bar()
{
T* t = NULL;
//do stuff
return *t;
}
template class Foo<int>;
template class Foo<float>;
template class Foo<double>;
template class Foo<long long>;
【问题讨论】:
标签: c++ templates header compilation-time explicit-instantiation