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

use*_*020 11 c++ templates compilation

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

// a.h
template<typename T> class A {...};
template class A<int>; // explicit template instantiation  to reduce compilation time
Run Code Online (Sandbox Code Playgroud)

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

Mik*_*our 18

在标头中声明实例化:

extern template class A<int>;
Run Code Online (Sandbox Code Playgroud)

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

template class A<int>;
Run Code Online (Sandbox Code Playgroud)

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


fgh*_*ghj 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>;
Run Code Online (Sandbox Code Playgroud)