Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Templates and ODR

The question is about the C++ documentation and standard documentation. Is in the following code the variable 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...)

like image 200
guest Avatar asked Nov 08 '22 00:11

guest


1 Answers

It is odr-used. [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.

[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]) [...]

We can stop here. Applying the lvalue-to-rvalue conversion to x does not yield a constant expression.

This violation of the ODR does not require a diagnostic ([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.

like image 80
T.C. Avatar answered Nov 15 '22 05:11

T.C.