static_assert of const Variable

我与影子孤独终老i 提交于 2019-12-08 02:55:49

问题


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:

error C2057: expected constant expression

I'm actually doing this correctly and visual-studio-2010 just hasn't properly implemented static_assert, right? In visual-studio-2017 it works as intended.


There has been some commentary of the differences between const and 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? I'm not as concerned about which compiler supports it, I'm concerned about whether it's defined under the C++ standard.


回答1:


foo > 0.0F is not a core constant expression:

  1. 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:

...

(2.7) an lvalue-to-rvalue conversion unless it is applied to

(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.2) a non-volatile glvalue that refers to a subobject of a string literal, or

(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.4) a non-volatile glvalue of literal type that refers to a non-volatile object whose lifetime began within the evaluation of 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:

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. LIVE (Usingconstexpr instead of const works too. LIVE)



来源:https://stackoverflow.com/questions/46961749/static-assert-of-const-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!