简体   繁体   English

非模板类与模板类的多个定义

[英]Multiple definitions of a non-template class vs. a template class

为什么编译器抱怨在多个.cpp文件中定义的非模板类,但是对于模板类来说很好,其定义在各种.cpp文件中重复(通过包含类的.inl文件),即使class是否在多个.cpp文件中显式实例化?

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. 我不是100%确定是否应该将显式模板实例化视为非模板函数。

模板函数是内联的,只要每个定义相同,就允许在多个编译单元中定义内联函数。

Do all compilers complain, always? 所有编译器总是抱怨吗? I've never seen one which did, and the standard doesn't allow it: you're allowed to define a class or a template once in each translation unit, as long as all of the definitions are identical. 我从来没有见过一个做过的,标准不允许它:只要所有定义都相同,你就可以在每个翻译单元中定义一个类或模板一次。 In fact, you're required to define the class in every translation unit which uses it in a way that requires it to be a complete type. 实际上,您需要在每个使用它的翻译单元中定义该类,使其成为一个完整的类型。 C++ does not have any mechanism for exporting class definitions to other translation units. C ++没有任何将类定义导出到其他翻译单元的机制。

Are you sure you're not confusing classes with functions. 你确定你没有把功能混淆。 You're not allowed to define a function more than once, unless it is inline. 除非是内联函数,否则不允许多次定义函数。 You still have to define a function template in each translation unit which uses it, and the same rules apply for function templates as for classes and class templates. 您仍然需要在每个使用它的翻译单元中定义一个函数模板,并且相同的规则适用于函数模板以及类和类模板。

Note that if you violate these rules, by defining the function in more than one translation unit, or by the definitions of the classes or templates not being tokenwise identical (after preprocessing, and including name binding), then you have undefined behavior. 请注意,如果违反这些规则,通过在多个转换单元中定义函数,或者类或模板的定义不是标记相同的(在预处理之后,包括名称绑定),那么您将具有未定义的行为。 The compiler (actually the linker) may complain about it, but it's not required: most complain about multiple definitions of a function, but I don't know of any which complain when the class or template definitions differ between translation units. 编译器(实际上是链接器)可能会抱怨它,但它不是必需的:大多数抱怨函数的多个定义,但我不知道在转换单元之间类或模板定义不同时会有什么抱怨。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM