Name: Anonymous 2020-01-21 9:21
I'm trying to write a smart pointer class, that points to a member of the original pointed to object. Is there a way to replace magic_old with something that does not depend on macros?
#include <type_traits>
#include <utility>
template <typename F> struct member_ptr_of {};
template <typename T, typename A> struct member_ptr_of<A T::*> { using type = T; };
template <typename P> struct derefs_to { using type = typename std::remove_reference<decltype(*P())>::type; };
template <typename T, typename A> struct derefs_to<A T::*> { using type = A; };
template <typename P, typename FP, FP fptr>
struct aliasing_ptr {
using T = typename member_ptr_of<FP>::type;
using F = typename derefs_to<FP>::type;
P ptr;
aliasing_ptr(P ptr) : ptr(std::move(ptr)) { }
auto operator * () -> F & { return (*ptr).*fptr; }
auto operator -> () -> F * { return &((*ptr).*fptr); }
};
#include <memory>
struct A { int i; A(int i) : i(i) {} };
#define magic_old(fp, p) aliasing_ptr< \
typename std::remove_reference<decltype(p)>::type, \
typename std::remove_reference<decltype(fp)>::type, \
fp>(p)
int main()
{
auto p = std::make_shared<A>(1);
auto ap1 = aliasing_ptr<std::shared_ptr<A>, int A::*, &A::i>(p);
auto ap2 = magic_old(&A::i, p);
(std::true_type)std::is_same<decltype(ap1), decltype(ap2)>::type();
//auto ap3 = magic<&A::i>(p);
}