如何使用显式模板实例化来减少编译时间?

时间:2014-10-08 01:09:19

标签: c++ templates compilation

建议使用显式模板实例化来减少编译时间。我想知道该怎么做。例如

// a.h
template<typename T> class A {...};
template class A<int>; // explicit template instantiation  to reduce compilation time

但是在包含a.h的每个翻译单元中,似乎都会编译A<int>。编译时间不会减少。如何使用显式模板实例化来减少编译时间?

2 个答案:

答案 0 :(得分:17)

在标题中声明实例化:

extern template class A<int>;

并在一个源文件中定义它:

template class A<int>;

现在它只会被实例化一次,而不是每个翻译单元,这可能会加快速度。

答案 1 :(得分:9)

如果您知道您的模板仅用于某些类型, 我们称之为T1,T2,你可以将实现移动到源文件, 像普通班一样。

//foo.hpp
template<typename T>
struct Foo {
    void f();
};

//foo.cpp
template<typename T>
void Foo<T>::f() {}

template class Foo<T1>;
template class Foo<T2>;
相关问题