This question is somewhat a continuation of this one I've posted.
What I was trying to do: my point was to allow access to private members of a base class A
in a derived class B
, with the following restraints:
- what I want to access is a structure -- an
std::map<>
, actually --, not a method; - I cannot modified the base class;
- base class
A
has no templated method I may overload as a backdoor alternative -- and I would not add such method, as it would be going against the second restraint.
As a possible solution, I have been pointed to litb's solution (post / blog), but, for the life of me, I haven't been able to reach an understanding on what is done in these posts, and, therefore, I could not derive a solution to my problem.
What I am trying to do: The following code, from litb's solution, presents an approach on how to access private members from a class/struct, and it happens to cover the restrictions I've mentioned.
So, I'm trying to rearrange this one code:
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;
}
To something that would allow me to do the following -- note I'm about to inherit the class, as the entries in the std::map<>
are added right after the initialization of the derived class B
, i.e., the std::map<>
isn't simply a static member of class A
with a default value, so I need to access it from a particular instance of B
:
// NOT MY CODE -- library <a.h>
class A {
private:
std::map<int, int> A_map;
};
// MY CODE -- module "b.h"
# include <a.h>
class B : private A {
public:
inline void uncover() {
for (auto it(A_map.begin()); it != A_map.end(); ++it) {
std::cout << it->first << " - " << it->second << std::endl;
}
}
};
What I'd like as an answer: I'd really love to have the above code working -- after the appropriate modifications --, but I'd be very content with an explanation on what is done in the first code block -- the one from litb's solution.
See Question&Answers more detail:os