I've just added an entry to my blog that shows how it can be done in a completely conforming way. Here is an example on how you use it for the following class
struct A {
private:
int member;
};
Just declare a tag name and instantiate a robber like the following example shows (my post shows the implementation of the robber). You can then access that member using a member pointer
struct Amem { typedef int type; };
template class rob;
int main() {
A a;
a.*result::ptr = 42; // Doh!
}
But actually, this doesn't show that c++'s access rules aren't reliable. The language rules are designed to protect against accidental mistakes - if you try to rob data of an object, the language by-design does not take long ways to prevent you.
The above is a way to access private and protected members in a conforming way. This one is another way to access protected members in a Standard conforming way. The basic idea is to use a member pointer
std::deque &getAdapted(std::stack &s) {
struct voyeur : stack
{ using stack::c; };
return s.*(&voyeur::c);
}
int main() {
std::stack s;
std::deque &adapted = getAdapted(s);
output(adapted); // print the stack...
}
No casting or type punning involved. It takes a pointer to a protected member of std::stack
through a class derived from it where that member name is public, so the compiler allows this. Then it uses it on a std::stack
object, which is allowed too.