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

后端 未结 2 1655
耶瑟儿~
耶瑟儿~ 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; // explicit instantiation declaration
    

提交回复
热议问题