Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 753
Curious Avatar asked Jun 30 '16 20:06

Curious


1 Answers

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.

like image 148
Brian Bi Avatar answered Oct 14 '22 17:10

Brian Bi