This is a tricky tactic to access a private member of class.
But I can’t get the point of declaration of friend get
inside struct A_member
?
#include <iostream>
struct A {
private:
int member;
};
template<typename Tag, typename Tag::type M>
struct Rob {
friend typename Tag::type get(Tag) {
return M;
}
};
// tag used to access A::member
struct A_member {
typedef int A::*type;
friend type get(A_member);
};
template struct Rob<A_member, &A::member>;
int main() {
A a;
a.*(get(A_member())) = 42; // write 42 to it
std::cout << "proof: " << a.*get(A_member()) << std::endl;
}
According to the cppreference:
(only allowed in non-local class definitions) Defines a non-member function, and makes it a friend of this class at the same time.
The explicit instantiation of struct Rob
has made the newly defined get
a non-member function, in the closest namespace, i.e. global namespace here. So can it be accessed directly in the main
?
Actually I have tried that, and it does not compile.
Back to the above code, it redeclare a friend get
inside the struct A_member
and then magically it works. What’s the purpose of this friend declaration? Is there some special c++ rule that I missed?