什么是C ++中的constexpr? [英] What is constexpr in C++?

查看:57
本文介绍了什么是C ++中的constexpr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的对 constexpr 概念感到困惑,因为我读过 constexpr 是在编译时评估的,所以与常规 const 相比,它对性能优化很有用。

I am really confused about a constexpr concept, as I have read constexpr is evaluated at compile time, so it is useful for performance optimization versus normal const.

constexpr int i = 0;
constexpr int& ri = i;

上面的代码从类型的表达式返回错误类型为'int&'的引用的无效初始化 'const int',为什么?

The above code returns an error "invalid initialization of reference of type 'int&' from expression of type 'const int'", why?

此外,下一个代码有错误:

Also, the next code has an error:

constexpr int i = 0;
constexpr int* ri = &i;

如果我将 constexpr 关键字替换为 const ,以上所有方法均正常工作。

If I replaced the constexpr keyword with const, all above worked correctly.

推荐答案

Re


,如果我将constexpr单词替换为以上所有const都能正常工作。

if I replaced the constexpr word with const all above worked correctly."

A const int * 本质上意味着(const int)* ,除了不能使用括号。 constexpr int * 表示 constepxr(int *)(ditto注意)。

A const int* essentially means (const int)*, except that you can't use parentheses that way. A constexpr int* means constepxr (int*) (ditto note).

这是因为 constexpr 不是该类型的一部分,您不能将类型命名为<例如,code> constexpr int ,而 const 是该类型的一部分。

This is because constexpr is not part of the type, you can't name the type constexpr int, say, while const is part of the type.

而不是

constexpr int i = 0;
constexpr int& ri = i;

试图声明 constexpr 对非<$的引用c $ c> const ,只需写

constexpr int i = 0;
constexpr int const& ri = i;

您可以倒读为 ri const int 的引用,即 constexpr (已评估

You can read that backwards as ri is a reference to a const int which is constexpr (evaluated at compile time).

附录

看来C ++ 14要求本地非静态 constexpr 对象具有自动存储期限,对假设规则进行优化以求模。

It ¹appears that C++14 requires local non-static constexpr objects to have automatic storage duration, modulo the as-if rule for optimization.

为此,即使代码可移植在所有编译器中,如果以上声明局部出现在函数中,请添加 static 以确保该对象所引用的对象的静态存储持续时间:

To cater for this, i.e. to make the code portable across compilers, if the above declarations appear locally in a function, add static to ensure static storage duration for the object that one refers to:

void oops()
{
    static constexpr int i = 0;      // Necessary with some compilers.
    constexpr int const& ri = i;
}

否则它可能无法编译,例如g ++,并且通过省略对 constexpr 的适当约束,这可能是 C ++ 14和C ++ 11标准。

Otherwise it may not compile with e.g. g++, and it's probably what the C++14 and C++11 standards require, by omission of suitable constraints on constexpr.


注意:

¹请参见讨论萨胡的答案

这篇关于什么是C ++中的constexpr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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