以下内容来自Access to private members: Safer nastiness一文,作者为Johannes Schaub - litb。
template<typename Tag, typename Tag::type M>
struct Rob {
friend typename Tag::type get(Tag) {
return M;
}
};
// use
struct A {
A(int a):a(a) { }
private:
int a;
};
// tag used to access A::a
struct A_f {
typedef int A::*type;
friend type get(A_f);
};
template struct Rob<A_f, &A::a>;
int main() {
A a(42);
std::cout << "proof: " << a.*get(A_f()) << std::endl;
}
由于get
函数没有在A
类中定义,因此如何从a
对象中调用get
函数?
编辑:
我不明白为什么get
函数必须将标签作为参数传递,而不能使用a.*get<A_f>()
。
=> 好的,这是由于ADL机制造成的。
template struct Rob<A_f, &A::a>;
这行代码上没有中止,并给出类似于"A::a在此上下文中是私有的"的提示。毕竟,该代码试图获取一个私有成员的指针。很奇怪。 - Nikos C.