Created
November 2, 2016 09:55
-
-
Save remyroez/d36845f0fb3455f27716682d63b47c30 to your computer and use it in GitHub Desktop.
private メンバにアクセス(写経)
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
#include <iostream> | |
// impl ---------- | |
template <typename T> | |
struct accessor { | |
static typename T::type value; | |
}; | |
template <typename T> | |
typename T::type accessor<T>::value; | |
template <typename T, typename T::type P> | |
struct deprivate { | |
deprivate() { accessor<T>::value = P; } | |
static deprivate instance; | |
}; | |
template <typename T, typename T::type P> | |
deprivate<T, P> deprivate<T, P>::instance; | |
template <typename T, typename U> struct private_member { using type = U T::*; }; | |
template <typename T, typename U> | |
auto get_private(const U &u) { return u.*accessor<T>::value; } | |
#define PRIVATE_TAG(CLASS, MEMBER) _private_tag$ ## CLASS ## $ ## MEMBER | |
#define PRIVATE_ACCESS(CLASS, MEMBER_T, MEMBER) \ | |
struct PRIVATE_TAG(CLASS, MEMBER) : private_member<CLASS, MEMBER_T> {}; \ | |
template struct deprivate<PRIVATE_TAG(CLASS, MEMBER), &CLASS::MEMBER>; | |
#define PRIVATE_GET(CLASS, MEMBER, INSTANCE) get_private<PRIVATE_TAG(CLASS, MEMBER)>(INSTANCE) | |
// usage ---------- | |
struct foo { | |
public: | |
foo(int value) : _value(value), _value2(456) {} | |
int value() const { return _value; } | |
private: | |
int _value; | |
int _value2; | |
}; | |
PRIVATE_ACCESS(foo, int, _value); | |
PRIVATE_ACCESS(foo, int, _value2); | |
int main() | |
{ | |
foo a(123); | |
std::cout << a.value() << std::endl; | |
std::cout << get_private<PRIVATE_TAG(foo, _value)>(a) << std::endl; | |
std::cout << get_private<_private_tag$foo$_value>(a) << std::endl; | |
std::cout << PRIVATE_GET(foo, _value, a) << std::endl; | |
std::cout << PRIVATE_GET(foo, _value2, a) << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
参考サイト