2014-10-08 65 views
9

建議使用顯式模板實例化來減少編譯時間。我想知道如何去做。例如如何使用顯式模板實例化來減少編譯時間?

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

但在A.H每個翻譯單元在內,似乎A<int>將被編譯。編譯時間不會減少。如何使用顯式模板實例化來減少編譯時間?

回答

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>; 
+0

不應該採用'template void Foo :: f(){}'的形式嗎?請注意'Foo ::'而不是'Foo ::' – Xupicor 2015-10-27 07:51:24

+1

你說得對。 – fghj 2015-10-27 16:31:28

15

聲明實例在標題:

extern template class A<int>; 

,並在一個源文件中定義它:

template class A<int>; 

現在它只會被實例化一次,而不是在每一個翻譯單元,這可能會加快事情了。

+0

酷不知道這 – 2014-10-08 01:28:40

+0

它會在所有的源文件被實例化顯式模板實例化定義指令('模板類A ;')。 – Constructor 2014-10-08 10:20:21

+1

@Constructor:確實。如果你做了答案所說的話,那隻會發生一次。 – 2014-10-08 15:49:02

相關問題