constness it not propagated for dependent types

Viewed 90

Why is it that for

struct A { int a };   
using B = const A;    // or typedef const A B;

decltype(B::a) evaluates to int and not const int. What chapter of the How to learn C++ in a life time am I missing?

1 Answers

Assuming you meant decltype(B::a), I do not see why you expect it to return const int.

decltype(x) roughly gives you the "type x was declared as", which in this case is int.

Here's an interesting example:

int main()
{
    B x{};
    static_assert(std::is_same_v<decltype(x.a), int>); // (0)
    static_assert(std::is_same_v<decltype((x.a)), const int&>); // (1)
}

(0) tells you that the declared type of x.a is indeed int, even though x is const.

(1) tells you that the value category of x.a is an lvalue, which happens to be const.

(Note that decltype behaves differently with parenthesized expressions.)

Related