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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With