Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't understand this line - dereferencing an address of private member variable or what?

Tags:

c++

stl

I asked a question while ago about accessing the underlying container of STL adapters. I got a very helpful answer:

template <class T, class S, class C>
    S& Container(priority_queue<T, S, C>& q) {
        struct HackedQueue : private priority_queue<T, S, C> {
            static S& Container(priority_queue<T, S, C>& q) {
                return q.*&HackedQueue::c;
            }
        };
    return HackedQueue::Container(q);
}

int main()
{
    priority_queue<SomeClass> pq;
    vector<SomeClass> &tasks = Container(pq);
    return 0;
}

Unfortunately, I couldn't understand this line:

return q.*&HackedQueue::c;

What does this line do? Also, how could that line access the private container in priority_queue that is passed to the function Container?

like image 222
Khaled Alshaya Avatar asked Sep 09 '09 16:09

Khaled Alshaya


1 Answers

Think of it like this:

(q).*(&HackedQueue::c);

First, you have HackedQueue::c, which is just the name of a member variable. Then you take &HackedQueue::c, which is a pointer to that member variable. Next you take q, which is just an object reference. Then you use the "bind pointer to member by reference" operator .* to bind the member variable referred to by the member-variable pointer using q as the this.

As to the private member issue, priority_queue::c is only protected, not private, so it should come as no surprise that when you derive from priority_queue, that you can access its protected members.

like image 98
Eclipse Avatar answered Sep 30 '22 14:09

Eclipse