What's the right way to specialize a template when using “extern template”?

后端 未结 2 1474
攒了一身酷
攒了一身酷 2020-12-15 18:40

I am hoping someone can point out the correct way to specialize a method in a template class while using \"extern template class\" and \"template class\" for explicit instan

2条回答
  •  时光取名叫无心
    2020-12-15 18:55

    Adding this answer to address the question in the title (template instantiation, and not necessarily template method instantiation).

    This much resembles function declaration/definition.

    • Explicit instantiation declaration: extern template class is a declaration and should generally go in the header.
    • Explicit instantiation definition: template class is a definition and should generally go in the cpp.
    • No code is generated in object files following the declaration.
    • Code is generated in the object file of the cpp that contained the definition.
    • Without explicit instantiation, implicit instantiation will take place when the template is actually used. This will happen in every compilation unit (object file) that uses the template.
    • Implicit instantiation won't take place if a declaration was encountered. This is the gist of this mechanism - avoid object code duplication caused by implicit instantiation that happened because the compiler didn't trust that there's a single compilation unit in charge of instantiating the template.

    More info here.

提交回复
热议问题