[英]static_assert of const Variable
I have this code:我有这个代码:
const float foo = 5.0F;
static_assert(foo > 0.0F, "foo must be greater than 0.");
But in visual-studio-2010 I get the error:但是在visual-studio-2010中我得到了错误:
error C2057: expected constant expression错误 C2057:预期的常量表达式
I'm actually doing this correctly and visual-studio-2010 just hasn't properly implemented static_assert
, right?我实际上是在正确地做这件事,而visual-studio-2010只是没有正确实现static_assert
,对吧? In visual-studio-2017 it works as intended.在visual-studio-2017 中,它按预期工作。
There has been some commentary of the differences between const
and constexpr
.有一些关于const
和constexpr
之间差异的评论。 I understand this difference, however many compilers support this use of static_assert
so I'll ask again, is this legal code or not?我理解这种差异,但是许多编译器都支持static_assert
这种使用,所以我再问一下,这段代码是否合法? I'm not as concerned about which compiler supports it, I'm concerned about whether it's defined under the C++ standard.我不关心哪个编译器支持它,我关心它是否是在 C++ 标准下定义的。
foo > 0.0F
is not a core constant expression : foo > 0.0F
不是核心常量表达式:
- An expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine, would evaluate one of the following expressions:表达式 e 是核心常量表达式,除非按照抽象机器的规则对 e 求值会求值以下表达式之一:
... ...
(2.7) an lvalue-to-rvalue conversion unless it is applied to (2.7) 左值到右值的转换,除非它应用于
(2.7.1) a non-volatile glvalue of integral or enumeration type that refers to a complete non-volatile const object with a preceding initialization, initialized with a constant expression, or (2.7.1) 整数或枚举类型的非易失性泛左值,它指的是一个完整的非易失性 const 对象,它具有前面的初始化,用常量表达式初始化,或
(2.7.2) a non-volatile glvalue that refers to a subobject of a string literal, or (2.7.2) 引用字符串文字的子对象的非易失性泛左值,或
(2.7.3) a non-volatile glvalue that refers to a non-volatile object defined with constexpr, or that refers to a non-mutable subobject of such an object, or (2.7.3) 非易失性泛左值,它指的是用 constexpr 定义的非易失性对象,或指的是此类对象的非可变子对象,或
(2.7.4) a non-volatile glvalue of literal type that refers to a non-volatile object whose lifetime began within the evaluation of e; (2.7.4) 文字类型的非易失性泛左值,它指的是一个非易失性对象,其生命周期开始于 e 的求值内;
foo
is of floating-point type, for foo > 0.0F
an lvalue-to-rvalue conversion on foo
is required, which doesn't match the above conditions, then foo > 0.0F
is not considered as constant expression : foo
是浮点类型, foo > 0.0F
左值到右值转换上foo
是必需的,它不符合上述条件,则foo > 0.0F
不被认为是常量表达式:
A constant expression is either a glvalue core constant expression that refers to an entity that is a permitted result of a constant expression (as defined below), or a prvalue core constant expression whose value satisfies the following constraints常量表达式要么是泛左值核心常量表达式,它指的是作为常量表达式(如下定义)的允许结果的实体,要么是其值满足以下约束的纯右值核心常量表达式
On the other hand, if declare foo
as integral type the code would be fine.另一方面,如果将foo
声明为整型,代码就可以了。 LIVE (Using constexpr
instead of const
works too. LIVE ) LIVE (使用constexpr
而不是const
作品了。 LIVE )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.