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

后端 未结 2 1652
耶瑟儿~
耶瑟儿~ 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:44

    When you put an explicit instantiation definition in the file A.cpp, how is the compiler supposed to know it's there when compiling main.cpp? The answer is that it can't, so it would still instantiate the templates used in main.cpp, and in your case using the explicit instantiation definition is useless and doesn't help.

    A declaration of an explicit instantiation says to the compiler "do not bother instantiating this template, I will do so myself, somewhere else in the program", and the definition is what fulfils that promise.

    The explicit instantiation must be defined exactly once, in only one file, but it can be declared multiple times in different files. This is nothing unique to templates, in C and C++ the same rules apply to (non-inline) functions: you can declare them multiple times in different files (usually by putting the declaration in a header) and then you must define the function exactly once, in one file.

    So to make your example work properly you should add a declaration in A.h:

    extern template class A<int>; // explicit instantiation declaration
    
    0 讨论(0)
  • 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<int> specialization:

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

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

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

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