为什么要使用C ++的< vector>模板化类不会违反一个定义规则? [英] Why C++'s <vector> templated class doesn't break one definition rule?

查看:61
本文介绍了为什么要使用C ++的< vector>模板化类不会违反一个定义规则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许是la脚的问题,但是我不明白!如果我在多个翻译单元(不同的.cpp)中包含< string> < vector> ,为什么它不破坏ODR?据我了解,每个.cpp的编译方式不同,因此将分别为每个目标文件生成vector的方法代码,对吗?因此,链接器应该检测到它并抱怨.即使不会(我怀疑这是模板的特例),当我将所有链接都链接在一起时,也会在每个单元中使用一个代码或一组不同的克隆代码吗?

Maybe its lame question, But I don't get it! If I include <string> or <vector> in multiple translation units (different .cpp) why it doesn't break the ODR? As far as I know each .cpp is compiled differently so vector's methods code will be generated for each object file separately, right? So linker should detect it and complain. Even If it won't (I suspect it's special case for templates) will it be using one code or different set of cloned code in each unit, when I link all together???

推荐答案

任何模板定义都不会破坏ODR的方式相同-mdash;ODR特别指出,模板定义可以在翻译单位之间重复,只要它们在字面上是重复的(并且由于它们是重复的,就不可能有冲突或模棱两可).

The same way any template definitions don't break the ODR — the ODR specifically says that template definitions may be duplicated across translation units, as long as they are literally duplicates (and, since they are duplicates, no conflict or ambiguity is possible).

[C ++ 14:3.2/6]:一个类类型(第9条),枚举类型(7.2),具有外部链接的内联函数(7.1)可以有多个定义.2),类模板(第14章),非静态函数模板(14.5.6),类模板的静态数据成员(14.5.1.3),类模板的成员函数(14.5.1.1)或模板专门化程序中未指定某些模板参数(14.7、14.5.5),前提是每个定义出现在不同的翻译单元中,并且定义满足以下要求 [..]

[C++14: 3.2/6]: There can be more than one definition of a class type (Clause 9), enumeration type (7.2), inline function with external linkage (7.1.2), class template (Clause 14), non-static function template (14.5.6), static data member of a class template (14.5.1.3), member function of a class template (14.5.1.1), or template specialization for which some template parameters are not specified (14.7, 14.5.5) in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements [..]

明确允许并有效地消除了在同一翻译单元中的< vector> 的多个包含物,这比" #ifndef "标头保护符更有可能.

Multiple inclusions of <vector> within the same translation unit are expressly permitted and effectively elided, more than likely by "#ifndef" header guards.

这篇关于为什么要使用C ++的&lt; vector&gt;模板化类不会违反一个定义规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆