【发布时间】:2012-10-20 22:21:38
【问题描述】:
来自Access to private members: Safer nastinessJohannes 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;
}
如何从a 对象调用get 函数,因为它没有在class A 中定义?
编辑:
我不明白为什么 get 必须有 Tag 作为参数而不是 a.*get<A_f>()
=> 好的,这是由于 ADL 机制
【问题讨论】:
-
当涉及到参数依赖查找 (ADL) 时,这似乎是一个奇怪的错误,我目前在我的黑莓上,无法使用它 - 但如果编译它应该(来自我的观点)被视为一个错误。
-
@hexist 我刚刚在 Clang (3.1) 和 Intel C++ (13.0.0) 上验证了这一点。
-
我认为核心问题是为什么编译器不会在
template struct Rob<A_f, &A::a>;上中止类似“A::a 在此上下文中是私有的”之类的内容。毕竟,代码试图获取指向私有成员的指针。很奇怪。 -
@hexist 将 Apple LLVM 4.1 添加到适用的列表中。在这里看到一个模式......
-
@JamesMcNellis,我认为你的链接是错误的。试试看:bloglitb.blogspot.com/2011/12/…