gpt4 book ai didi

c++ - const变量的static_assert

转载 作者:行者123 更新时间:2023-12-02 10:29:42 25 4
gpt4 key购买 nike

我有以下代码:

const float foo = 5.0F;

static_assert(foo > 0.0F, "foo must be greater than 0.");

但是在 中,我得到了错误:

error C2057: expected constant expression



我实际上在正确执行此操作,而 尚未正确实现 static_assert,对吗?在 中,它可以按预期工作。

有人对 constconstexpr之间的区别进行了评论。我理解这种差异,但是许多编译器支持 static_assert的这种用法,所以我再问一遍,这是合法代码吗?我不太关心哪个编译器支持它,而是担心它是否在C++标准下定义。

最佳答案

foo > 0.0F不是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是浮点类型,对于 foo > 0.0F,需要对 foo进行从左值到右值的转换,但不符合上述条件,因此 foo > 0.0F不被视为 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



另一方面,如果将 foo声明为整数类型,则该代码会很好。 LIVE(也可以使用 constexpr代替 constLIVE)

关于c++ - const变量的static_assert,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62734323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com