Reputation: 4850
Consider this code:
struct AA
{
int& rr;
};
Is there a way to obtain pointer (or maybe reference) to AA::rr
in order to obtain this?
AA* aa;
auto mm = &AA::rr; // error: cannot create pointer to reference member ‘AA::rr’
aa ->* mm;
Also in gcc-7.0.1
decltype(AA::mm)
is just int&
. Is this according to the standard? And does this make sense?
EDIT
Sorry guys, I formulated the question not quite well. No complaints to the fact that references are not objects or that there is no such thing as pointer to a reference. The goal is quite selfish. Given struct AA { int& rr; };
I just want to have a function like this:
template < typename Class, typename Member >
void test(Member Class::*) { }
that when calling test(&AA::rr)
I want Class
to be AA
and Member
to be int&
or int
. So I don't even need the pointer itself but its type that will allow to retrieve the class type and the member type.
Upvotes: 12
Views: 3197
Reputation: 381
Picture speaks a thousand words
References doesn't really have a container in the memory, they serves more like an alias to the original variable, thus you cannot get pointer to reference because references doesn't have their own memory location.
However, you can get the address of reference, which is the variable it is referencing. In this example, if you cout &rx and &x, they are the same.
So probably you would want to get a pointer to the object it is referencing, rather than pointer to reference
Upvotes: 4
Reputation: 238491
How to obtain pointer to reference (member)?
You cannot obtain a pointers to (or references to, or arrays of) references. There is no such type as "pointer to reference" in C++. This is because references are not required to have storage, so there might not even be an address where the reference is stored.
When you apply addressof operator on a reference, what you get is the address of the object that is referred to.
Upvotes: 11