Search code examples
c++referenceconstantsc++14decltype

Why member variables of a const object are not const


Just asked a similar question which boils down to this one.

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

Why do the templates do not become const int instead of int?


Solution

  • decltype gives you the "declared type" of the operand when it isn't enclosed in an extra set of parentheses.

    To get the actual type of the expression, that is, const int, you would have to write decltype((a.a)) and so on.

    decltype always returns a reference type for lvalue expressions other than names.