How to use explicit template instantiation to reduce compilation time?

后端 未结 2 1357
夕颜
夕颜 2021-01-04 06:48

It was suggested to use explicit template instantiation to reduce compilation time. I am wondering how to do it. For example

// a.h
template         


        
相关标签:
2条回答
  • 2021-01-04 07:25

    Declare the instantiation in the header:

    extern template class A<int>;
    

    and define it in one source file:

    template class A<int>;
    

    Now it will only be instantiated once, not in every translation unit, which might speed things up.

    0 讨论(0)
  • 2021-01-04 07:46

    If you know that your template will be used only for certain types, lets call them T1,T2, you can move implementation to source file, like normal classes.

    //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 讨论(0)
提交回复
热议问题