C++11: Explicit instantiation declaration vs. explicit instantiation definition

后端 未结 2 1653
耶瑟儿~
耶瑟儿~ 2021-02-05 05:04

What is the difference between the C++03\'s explicit template\'s instantiation definition and C++11\'s explicit template\'s instantiation declaration

2条回答
  •  灰色年华
    2021-02-05 05:55

    An explicit instantiation declaration (an extern template) skips implicit instantiation step: the code that would otherwise cause an implicit instantiation instead uses the explicit instantiation definition provided elsewhere (resulting in link errors if no such instantiation exists). This can be used to reduce compilation times by explicitly declaring a template instantiation in all but one of the source files using it, and explicitly defining it in the remaining file. Source

    Here a declaration in main.cpp or A.h would have prevented main.cpp from generating (at compile time) code based on what parts of the template are visible, namely an A.h-based A specialization:

    class A
    {
    public:
        A(int t);
    private:
        int _t;
    };
    

    However the main.cpp code does need to know that A::A(int) exists which means it must perform some sort of instantiation in order to learn all A members, which is exactly what an A.h-based A instantiation would do.

    So yeah not exactly obvious how it is useful here - though subject to per-compiler/platform profiling.

提交回复
热议问题