Duplicate c++ template instantiations

前端 未结 4 766
迷失自我
迷失自我 2020-12-17 16:16

Is it possible for the compiler to duplicate instantiations of a same template across several translation units?

For instance, if you have a.cpp which use a st

相关标签:
4条回答
  • 2020-12-17 16:47

    As sharptooth says, the final binary will only contain one instantiation. But the templates will still be instantiated everytime they are encountered in a compilation unit. If you want some compilation speed, in C++0x we get the extern templates. It works like normal extern variables, in that it has to be specified in at least one compilation unit, but the compiler wont instantiate the template in this unit. See here and this draft (14.7.2 [temp.explicit]) for more infos.

    0 讨论(0)
  • 2020-12-17 16:57

    I think that the compiler uses the same mechanism as with member functions of ordinary classes. It can make them inline and I presume that it leaves information around that the linker uses to sort it out for the final binary.

    The only difference is that the compiler 'writes' the definitions - that is the 'instantiation' of a template - but it manages to make exactly the same instantiation whilst compiling either of a.cpp or b.cpp

    0 讨论(0)
  • 2020-12-17 16:59

    This can happen while the project is being compiled, so different .obj files will have copies of the same instantiation. When the binary is linked the linker will eliminate all redundant copies of an instantiation, so the end binary will have only one copy.

    0 讨论(0)
  • 2020-12-17 17:08

    It is possible, but only if you explicitly instantiate them, but then you will get a linker errors :

    // header.hpp
    template< typename T >
    class A
    {
    };
    
    // source1.cpp
    template class A< int >;
    
    // source2.cpp
    template class A< int >;
    

    If you are not explicitly instantiating templates, then any decent linker will easily eliminate copies.

    0 讨论(0)
提交回复
热议问题