刚刚问了一个类似的问题,归结为这个问题。
#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
始终为名称以外的左值表达式返回引用类型。
关于c++ - 为什么const对象的成员变量不是const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38133079/