c++ - 为什么右值不能分配给 constexpr 引用变量

标签 c++ c++11 c++14 constexpr

我有以下代码

constexpr int into(int a,int b)
{
  int c=a*b;
  return c;
}

int main()
{
 constexpr int &n=into(5,5);

}

并且我已经阅读(在 MSDN 中)

The keyword constexpr was introduced in C++11 and improved in C++14. It means constant expression. Like const, it can be applied to variables so that a compiler error will be raised if any code attempts to modify the value.

看完之后,我以为constexpr可以用来代替const,但是对于上面的代码,我得到一个编译器错误说明

`int main()':
invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'`

constexpr 被替换为 const 时,它工作正常。我不明白这种行为;有人可以解释一下吗?

最佳答案

不同于const , 适用于 int , constexpr关键字将 const 直接应用于引用类型的变量 int& , 无效。

typedef int &int_ref;

int main() {
    int x = 1;
    int &a = x;          // OK
    int_ref b = x;       // OK, int_ref is 'int &'
    const int &c = 1;    // OK, reference to const int
    const int_ref d = 1; // error: type of d is 'int &'
                         // qualifier on reference are being ignored
}

constexpr int &nconstexpr int_ref n是一样的, 同时 const int &nconst int_ref n有不同的限定词。

关于c++ - 为什么右值不能分配给 constexpr 引用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37003573/

相关文章:

c++ - 是否可以在 OpenSUSE 上降级 glibc?

c++ - 将 const 函数引用绑定(bind)到 lambda

c++ - 如何在不使用 C++0x auto 的情况下实现这种类型特定的对象生成器

c++ - 解决此模板分辨率歧义的正确方法是什么?

c++ - 内部和外部重载 C++ 运算符之间的区别

c++ - 在 C++ 中从不同的线程写入文件

multithreading - std::thread C++ 11 无法解释为什么

c++ - auto&& 从 C++ lambda 返回类型

c++ - 递归尾随返回类型的名称解析

c++ - 奇怪的相同数字