Multiple class definitions without template and template class

Why do compilers complain about a class without a template defined in several .cpp files, but fine with a template class whose definition is duplicated in different .cpp files (by including the class .inl file) even if the class is explicitly instantiated into even several .cpp files?

+4
source share
3 answers

Template functions are built-in, and built-in functions are allowed to be defined in several compilation units if each definition is identical.

+1
source

The case without a template is that in this case your program violates one definition rule, so the linker (and not the compiler) will complain about several definitions.

For templates, on the other hand, the language indicates that this should work, and the linker sorts what to do. I am not 100% sure if explicit template creation should be handled in the same way as a function without a template.

+3
source

Do compilers always complain? I have never seen what I did, and the standard does not allow this: you can define a class or template once in each translation unit, if all the definitions are identical. In fact, you need to define a class in each translation unit that uses it in such a way that it is a full type. C ++ has no mechanism for exporting a definition class for other translation units.

Are you sure you are not confusing classes with functions. You are not allowed to define a function more than once, unless it is built-in. You still need to define a function template in each translation unit that uses it, and the same rules apply for function templates as for classes and class templates.

Please note that if you break these rules by defining a function in more than one translation unit, or if class definitions or templates are not identical (after preprocessing and including name binding), then you have undefined behavior. The compiler (actually the linker) may complain about this, but this is not required: most complain about several function definitions, but I don’t know anyone who complains when the class or template definitions differ from each other in translation units.

0
source

All Articles