我无法理解这一行 - 取消引用私有成员变量的地址还是什么?
我不久前问了一个问题 关于访问STL适配器的底层容器。我得到了一个非常有用的答案:
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;
}
不幸的是,我无法理解这一行:
return q.*&HackedQueue::c;
这条线有什么作用?另外,该行如何访问传递给函数 Container
的 priority_queue
中的私有容器?
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可以这样想:
首先,您有 HackedQueue::c,它只是一个成员变量的名称。然后,您获取 &HackedQueue::c,它是指向该成员变量的指针。接下来,您采用
q
,它只是一个对象引用。然后,使用“通过引用将指针绑定到成员”运算符.*
来绑定成员变量指针引用的成员变量,使用q
作为this
。至于私有成员问题,
priority_queue::c
仅受保护,而不是私有,因此当您从priority_queue
派生时,您可以访问它,这应该不足为奇其受保护的成员。Think of it like this:
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 usingq
as thethis
.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 frompriority_queue
, that you can access its protected members.