将const分配给constexpr变量 [英] Assign a const to a constexpr variable

查看:145
本文介绍了将const分配给constexpr变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图运行基于constexpr的程序.

I tried to run a program based on constexpr.

代码:-

#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;
}

在我所著的书中,提到如果将const分配给constexpr变量,则会出错.

In the book I follow, it is mentioned that if you assign a const to a constexpr variable, it is an error.

但是我的程序编译时没有任何抱怨.

But my program compiles without any complaints.

我想念什么吗?

推荐答案


修订

celtschk在问题下方的评论中指出了一个要点.也就是说,您没有分配代码中的任何内容.您只是在初始化.从const分配到constexpr确实是错误.因此,如果那是您的书所说的,那么那是不正确的.但是,这将是一个奇怪的观点,因为在另一个方向(从constexprconst)进行分配也是一个错误.无论如何,其余的答案是在假设您说分配"时表示初始化"的.

celtschk made a good point in the comments below the question. 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. 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. Anyway, the rest of the answer is under the assumption that when you said "assign", you meant "initialize".

修正终止

您的书不正确(假设您没有错误地解释书中所说的内容).用常量表达式初始化的const积分本身就是常量表达式.因此i是一个常量表达式,可用于进一步初始化其他常量表达式.

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. So i is a constant expression, and can be used to further initialize other constant expressions.

引用标准5.19/2

quoth the standard, 5.19/2

条件表达式e是核心常量表达式,除非 按照抽象机(1.9)的规则对e求值, 将评估以下表达式之一:
...
—左值到右值转换(4.1),除非将其应用于:
...
—整数或枚举类型的非易失性glvalue,它引用具有常量初始化的非易失性const对象,并使用常量表达式进行初始化
...

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:
...
— an lvalue-to-rvalue conversion (4.1) unless it is applied to:
...
— 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
...

但是,请注意,没有用常量表达式初始化的const当然不是常量表达式:

However, note that a const which is not initialized with a constant expression, is of course not a constant expression:

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

还请注意,此 only 仅适用于整数和枚举类型.不是,例如浮点数和双打.

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

尽管某些编译器可能允许这样做(我相信MSVC可以这样做)

Although some compilers might allow that (I believe MSVC does)

这篇关于将const分配给constexpr变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆