在 C++11 中,当预处理指令形式为...
#if expr
...遇到,expr
被评估为 constant-expression
如 16.1 [cpp.cond]
中所述.
这是在 expr
上的宏替换之后完成的,它的标识符(和关键字)被 0 替换,它的 preprocessing-tokens
转换为 tokens
, defined
运算符被评估,等等。
我的问题是当 expr
中的一个标记时会发生什么是 user-defined-literal
?
用户定义字面量类似于函数调用,但函数调用不能出现在expr
中(我认为),作为标识符替换的副作用。然而技术上user-defined-literals
能活下来。
我怀疑这是一个错误,但我不太明白如何从标准中得出结论?
也许是在第 16 条上添加用户定义文字的(迂腐的)影响 [cpp]
只是被忽略了?
还是我遗漏了什么?
更新:
举例说明:
这个预处理的目的是什么:
#if 123_foo + 5.5 > 100
bar
#else
baz
#endif
bar 或 baz 还是错误?
GCC 4.7 报告:
test.cpp:1:5: error: user-defined literal in preprocessor expression
所以它认为这是一个错误。这可以引用标准来证明吗?或者这只是“隐式”?
最佳答案
In C++11 when a preprocessing directive of the form...
#if expr ...
is encountered,expr
is evaluated as aconstant-expression
as described in16.1 [cpp.cond]
.This is done after macro replacement on
expr
, its identifiers (and keywords) are replaced by0
, itspreprocessing-tokens
are converted totokens
,defined
operator is evaluated, and so on.My question is what happens when one of the
tokens
inexpr
is auser-defined-literal
?
程序格式错误。
我的论点的核心来自于 16.1/1
脚注 147
中的观察,即在翻译阶段 4 中没有标识符
除了宏名称。
参数:
根据 2.14.8 [lex.ext]/2
A
user-defined-literal
is treated as a call to aliteral operator
orliteral operator template
(13.5.8)
.
因此,即使在 16.1/4
中描述的所有替换之后,我们仍有对(运算符)函数的剩余调用。 (其他尝试,例如使用 constexpr
函数,将因将所有非宏 identifiers
替换为 0
而受阻。)
因为这发生在翻译阶段 4,所以还没有定义甚至声明函数;尝试查找 literal-operator-id
一定会失败(有关类似的论点,请参阅 16.1/1
中的脚注 147)。
从稍微不同的角度来看,5.19/2
我们发现:
A
conditional-expression
is acore constant expression
unless it involves one of the following as a potentially evaluated subexpression (3.2) [...]:
- [...]
- an invocation of a function other than a constexpr constructor for a literal class or a constexpr function;
- an invocation of an undefined constexpr function or an undefined constexpr constructor [...];
据此,在常量表达式
中使用用户定义的文字
需要defined和constexpr literal operator
,在翻译阶段 4 中同样无法使用。
gcc 拒绝这个是对的。
关于c++ - 使用用户定义的文字有条件地包含在 C++11 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14915238/