Created
December 15, 2020 05:02
-
-
Save hsupu/faccbf64ff1d5bddecdf55333ae1a37e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// library | |
#pragma GCC diagnostic push | |
#pragma GCC diagnostic ignored "-Wnon-template-friend" | |
template<typename Tag, typename Tag::type MemberPointer> | |
struct Rob { | |
friend decltype(MemberPointer) access(Tag) { return MemberPointer; } | |
}; | |
template<typename Tag, typename Type> | |
struct TagBase | |
{ | |
using type = Type; | |
friend type access(Tag); | |
}; | |
#pragma GCC diagnostic pop | |
// example | |
#include <cstdio> | |
class A | |
{ | |
private: | |
int m_i0; | |
int m_i1; | |
bool m_b; | |
}; | |
struct A_m_i0 : TagBase<A_m_i0, int A::*> {}; | |
struct A_m_i1 : TagBase<A_m_i1, int A::*> {}; | |
struct A_m_b : TagBase<A_m_b, bool A::*> {}; | |
template struct Rob<A_m_i0, &A::m_i0>; // KEY!!! must be template instantiation | |
template struct Rob<A_m_i1, &A::m_i1>; // KEY!!! must be template instantiation | |
template struct Rob<A_m_b, &A::m_b>; // KEY!!! must be template instantiation | |
int main() { | |
A a; | |
a.*access(A_m_i0()) = 42; | |
fprintf(stdout, "%d\n", a.*access(A_m_i0())); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment