I've come across this approach (as one of the solutions to a programming task in a C++ course) a few days ago.
#include <iostream>
struct C {
C(int i) { m_i = i; }
private:
int m_i;
};
template<typename Tag, int C::* M>
struct Rob {
friend
int C::* get(Tag) {
return M;
}
};
template<typename D>
struct AcessorTag {
typedef D C::*type;
};
template struct Rob<AcessorTag<int>, &C::m_i>;
int &get_c(C &cls) {
return cls.*get(AcessorTag<int>());
}
int main()
{
C c(13);
std::cout << get_c(c);
return 0;
}
Can you please explain why this code compiles? Pretty much all that happens here is 1) we pass pointer-to-member as an argument to a struct template 2) we declare a friend function that just returns that pointer to member.
Is this standard C++? (I have tested on VS 2015)
The get
function is a friend of struct Rob<>
but it isn't a frient of struct C
. Anyway, struct C
appears to have no friends so how come its private member is accessible?
Thanks!