【问题标题】:How to use explicit template instantiation to reduce compilation time?如何使用显式模板实例化来减少编译时间?
【发布时间】:2014-10-08 01:09:19
【问题描述】:

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

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

但是在每个包含 a.h 的翻译单元中,似乎 A&lt;int&gt; 将被编译。编译时间没有减少。如何使用显式模板实例化来减少编译时间?

【问题讨论】:

    标签: c++ templates compilation


    【解决方案1】:

    在头部声明实例化:

    extern template class A<int>;
    

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

    template class A<int>;
    

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

    【讨论】:

    • 酷不知道这个
    • 它将在所有源文件中使用显式模板实例化定义指令 (template class A&lt;int&gt;;) 进行实例化。
    • @Constructor:确实。如果你按照答案所说的去做,那只会发生一次。
    • 我只想指出,显式模板实例化 declaration 不能很好地保护模板的多个实例化(意外或有意)。
    • 您能否提供一个关于良好保护的提示?有吗?我通常使用 2 个头文件——一个包含模板代码,另一个包含第一个并且仅包含“外部模板”显式规范声明。然后源文件包含第一个并进行显式声明,所有其他源文件包含第二个并带有“外部模板”声明。
    【解决方案2】:

    如果您知道您的模板将仅用于某些类型, 让我们称它们为 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>;
    

    【讨论】:

    • 实现不应该是template &lt;typename T&gt; void Foo&lt;T&gt;::f() { }的形式吗?注意Foo&lt;T&gt;:: 而不是Foo::
    猜你喜欢
    • 2010-10-08
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    • 2020-10-13
    • 2022-08-17
    • 1970-01-01
    • 2014-06-06
    • 2011-01-16
    相关资源
    最近更新 更多