为什么const对象的成员变量不是const
Why member variables of a const object are not const
刚刚问了一个类似的问题,归结起来就是这个。
#include <iostream>
using namespace std;
struct A {
A() : a{1} {};
int a;
};
template <typename Which>
struct WhichType;
int main() {
const A a;
const A& a_ref = a;
const A* a_ptr = &a;
WhichType<decltype(a.a)> which_obj; // template evaluates to int
WhichType<decltype(a_ref.a)> which_ref; // template evaluates to int
WhichType<decltype(a_ptr->a)> which_ptr; // template evaluates to int
return 0;
}
为什么模板不变成const int
而变成int
?
decltype
给出了操作数的"声明类型",当它没有被额外的括号括起来时。
要获得表达式的实际类型,即const int
,您必须编写decltype((a.a))
,以此类推。
decltype
总是返回左值表达式的引用类型,而不是名称。
当传递标识符(或成员)的名称时,它返回声明的类型。
当传递一个不同的表达式时,它返回更接近你想要的结果,但是引用限定。
WhichType<std::remove_reference_t<decltype((a_ptr->a))>> which_ptr; // template evaluates to const int!
生活的例子或者如果您想要l/r值:
WhichType<decltype((a_ptr->a))> which_ptr2; // template evaluates to const int&
WhichType<decltype(((const A){}.a))> which_ptr3; // template evaluates to const int
你可以在这里添加&&
,使它成为一个"真正的"右值引用。
WhichType<decltype(((A){}.a))&&> which_ptr4; // template evaluates to int&&!
生活例子。
相关文章:
- 在内存不足之前,我可以声明多少个 const 变量?
- 当设置为 const 变量时使用 nullptr
- 声明与 const 变量和成员函数相同的标识符
- const变量是否可以在具有默认值的参数中赋值(作为可选参数)
- 编译器在传递 const 变量时返回错误:模板参数不是常量表达式
- 在成员函数之间传递const变量为数组的索引
- 为什么静态常量字符 * const 变量在为左值时可绑定到右值引用参数
- C 编译器可以执行用于返回值的命名const变量的RVO
- 如何访问一系列const变量作为const数组
- C 错误C3892:您无法分配const变量
- 是否可以在C++中推迟 const 变量的初始化,例如 Java 的"blank final"功能?
- 为什么将FMTFLAG指定两次 - 作为枚举的一部分,而另一个实例为静态const变量
- 使用非const变量代替所需的const变量(C )
- 使用const变量时,非静态数据成员的使用无效
- 定义,初始化全局const变量是安全的吗?
- const vs non-const变量一旦分配就没有变化
- 为什么设置const变量(将以相同的值存储)会导致不同的结果
- CPP中的私有静态常规成员变量与const变量
- 在避免新分配的同时,const变量的复杂初始化
- 如何通过其地址更改const变量的值