简体   繁体   English

模板和ODR

[英]Templates and ODR

The question is about the C++ documentation and standard documentation. 问题是关于C ++文档和标准文档。 Is in the following code the variable x odr-used? 在下面的代码中是变量x odr-used?

extern int x;
template<class T> T f() { return x; }

It seems to me it is not used, bud where it is stated in documents? 在我看来它没有被使用,芽在文件中说明了什么? (there is the statement, that appearance x in expression is odr-use, but...) (有声明,表达中的外观x是odr-use,但......)

It is odr-used. 它使用得很多。 [basic.def.odr]/2: [basic.def.odr] / 2:

An expression is potentially evaluated unless it is an unevaluated operand or a subexpression thereof. 除非它是未评估的操作数或其子表达式,否则可能会评估表达式。

Thus the expression x is potentially evaluated . 因此, 可能评估表达式x

[basic.def.odr]/4: [basic.def.odr] / 4:

A variable x whose name appears as a potentially-evaluated expression ex is odr-used by ex unless applying the lvalue-to-rvalue conversion ([conv.lval]) to x yields a constant expression ([expr.const]) [...] 变量x ,其名称显示为潜在评估表达exODR-使用 ex ,除非施加左值到右值转换([conv.lval])来x产生一个常量表达式([expr.const])[。 ..]

We can stop here. 我们可以在这里停下来 Applying the lvalue-to-rvalue conversion to x does not yield a constant expression. 将lvalue-to-rvalue转换应用于x不会产生常量表达式。

This violation of the ODR does not require a diagnostic ([basic.def.odr]/10): 违反ODR不需要诊断([basic.def.odr] / 10):

Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program outside of a discarded statement; 每个程序应该只包含每个非内联函数或变量的一个定义,该函数或变量在废弃语句之外的程序中使用。 no diagnostic required. 无需诊断。


Even assuming for the sake of argument that f does not odr-use x until/unless a specialization is generated, it still won't help the program, because the program is also ill-formed NDR if "no valid specialization can be generated for a template" ([temp.res]/8), and since every valid specialization of f undoubtedly odr-uses x , no valid specialization can be generated if a definition of x is not present in the program. 甚至假设为了论证f不会使用x直到/除非生成特化,它仍然无法帮助程序,因为如果“无法生成有效的专业化,程序也是格式错误的NDR”模板“([temp.res] / 8),并且由于f每个有效特化无疑使用了x ,如果程序中不存在x的定义,则不能生成有效的特化。

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

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