条件包含:整数常量表达式是无限的?
Conditional inclusion: integral constant expression is unlimited?
根据 C++11(及更新版本),此代码有效:
#if 1.0 > 2.0 ? 1 : 0
#endif
然而,大多数(如果不是全部)C++ 编译器拒绝它:
$ echo "#if 1.0 > 2.0 ? 1 : 0" | g++ -xc++ - -std=c++11 -pedantic -c
<stdin>:1:5: error: floating constant in preprocessor expression
<stdin>:1:11: error: floating constant in preprocessor expression
N4849 有这个(强调):
The expression that controls conditional inclusion shall be an integral constant expression except that identifiers (including those lexically identical to keywords) are interpreted as described below143 and it may contain zero or more defined-macro-expressions and/or has-include-expressions and/or has-attribute-expressions as unary operator expressions.
和这个(强调):
An integral constant expression is an expression of integral or unscoped enumeration type, implicitly converted to a prvalue, where the converted expression is a core constant expression.
1.0 > 2.0 ? 1 : 0
是整数常量表达式。
那么,C++ 标准在哪里禁止在控制条件包含的表达式中使用浮点文字(例如)?
理查德·史密斯的回答:
This is an error in the standard wording. See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1436 for details and a proposed fix -- though that fix is known to be wrong too (it permits lambda-expressions).
根据 C++11(及更新版本),此代码有效:
#if 1.0 > 2.0 ? 1 : 0
#endif
然而,大多数(如果不是全部)C++ 编译器拒绝它:
$ echo "#if 1.0 > 2.0 ? 1 : 0" | g++ -xc++ - -std=c++11 -pedantic -c
<stdin>:1:5: error: floating constant in preprocessor expression
<stdin>:1:11: error: floating constant in preprocessor expression
N4849 有这个(强调):
The expression that controls conditional inclusion shall be an integral constant expression except that identifiers (including those lexically identical to keywords) are interpreted as described below143 and it may contain zero or more defined-macro-expressions and/or has-include-expressions and/or has-attribute-expressions as unary operator expressions.
和这个(强调):
An integral constant expression is an expression of integral or unscoped enumeration type, implicitly converted to a prvalue, where the converted expression is a core constant expression.
1.0 > 2.0 ? 1 : 0
是整数常量表达式。
那么,C++ 标准在哪里禁止在控制条件包含的表达式中使用浮点文字(例如)?
理查德·史密斯的回答:
This is an error in the standard wording. See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1436 for details and a proposed fix -- though that fix is known to be wrong too (it permits lambda-expressions).