Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple definitions of a non-template class vs. a template class

Why do compilers complain about a non-template class defined in multiple .cpp files but are fine with a template class the definition of which is duplicated across various .cpp files (via inclusion of the .inl file of the class), even if the class is explicitly instantiated in even multiple .cpp files?

like image 922
Desmond Hume Avatar asked Jul 10 '12 15:07

Desmond Hume


1 Answers

The non-template case is because in that scenario your program violates the one definition rule so the linker (not compiler) will complain about multiple definitions.

For templates on the other hand, the language specifies that this must work and the linker sorts out what to do. I'm not 100% sure if an explicit template instantiation should be treated the same as a non-template function though.

like image 53
Mark B Avatar answered Oct 11 '22 12:10

Mark B