简体   繁体   English

将const分配给constexpr变量

[英]Assign a const to a constexpr variable

I tried to run a program based on constexpr . 我试图运行基于constexpr的程序。

Code:- 码:-

#include <iostream>
using namespace std;

int main()
{

        const int i = 10;
        constexpr int j = 10;

        constexpr int val1 = i;
        constexpr int val2 = j; 

        return 0;
}

In the book I follow, it is mentioned that if you assign a const to a constexpr variable, it is an error. 在我所著的书中,提到如果将const分配给constexpr变量,则会出错。

But my program compiles without any complaints. 但是我的程序编译时没有任何抱怨。

Am I missing something? 我想念什么吗?


Ammendment 修正案

celtschk made a good point in the comments below the question. Celtschk在问题下方的评论中指出了一个好观点。 That is, you are not assigning to anything in your code. 也就是说,您没有分配代码中的任何内容。 You are only initializing. 您只是在初始化。 Assigning from a const to a constexpr is indeed an error. const分配给constexpr确实是一个错误。 So if that's what your book said, then it was not incorrect. 因此,如果那是您的书所说的话,那是不正确的。 However, this would be a strange point to make, since assigning in the other direction (from a constexpr to a const ) is also an error. 但是,这将是一个奇怪的观点,因为在另一个方向(从constexprconst )赋值也是一个错误。 Anyway, the rest of the answer is under the assumption that when you said "assign", you meant "initialize". 无论如何,其余的答案是在假设您说“分配”时表示“初始化”的假设。

End of Ammendment 修正案结束


Your book is incorrect (assuming you are not incorrectly paraphrasing what it said). 您的书不正确(假设您没有错误地解释其内容)。 A const integral which is initialized with a constant expression, is itself a constant expression. 用常量表达式初始化的const积分本身就是常量表达式。 So i is a constant expression, and can be used to further initialize other constant expressions. 所以i是一个常数表达式,可以用来进一步初始化其他常数表达式。

quoth the standard, 5.19/2 引用标准,5.19 / 2

A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine (1.9), would evaluate one of the following expressions: 条件表达式e是核心常数表达式,除非按照抽象机(1.9)的规则对e的求值将对以下表达式之一求值:
... ...
— an lvalue-to-rvalue conversion (4.1) unless it is applied to: —左值到右值转换(4.1),除非将其应用于:
... ...
— a non-volatile glvalue of integral or enumeration type that refers to a non-volatile const object with a preceding initialization, initialized with a constant expression —整数或枚举类型的非易失性glvalue,它引用具有常量表达式且已进行初始化的非易失性const对象
... ...

However, note that a const which is not initialized with a constant expression, is of course not a constant expression: 但是,请注意,没有用常量表达式初始化的const当然不是常量表达式:

int a = 10;
const int b = a;
constexpr int c = b; // error

Also note that this only applies to integer and enum types. 另请注意,这适用于整数和枚举类型。 Not, for example floats and doubles. 否,例如浮点数和双打。

const float a = 3.14;
constexpr float b = a; // error

Although some compilers might allow that (I believe MSVC does) 尽管某些编译器可能允许这样做(我相信MSVC可以)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM