How to get a class (object type) from a pointer to a method

I have a pointer to a method:

struct A { int method() { return 0; } };
auto fn = &A::method;

I can get the return type by std :: result_of, but how can I get the method class owner from fn?

+4
source share
2 answers

Try the following:

template<class T>
struct MethodInfo;

template<class C, class R, class... A>
struct MethodInfo<R(C::*)(A...)> //method pointer
{
    typedef C ClassType;
    typedef R ReturnType;
    typedef std::tuple<A...> ArgsTuple;
};

template<class C, class R, class... A>
struct MethodInfo<R(C::*)(A...) const> : MethodInfo<R(C::*)(A...)> {}; //const method pointer

template<class C, class R, class... A>
struct MethodInfo<R(C::*)(A...) volatile> : MethodInfo<R(C::*)(A...)> {}; //volatile method pointer
+3
source

You can match it using the specialization of the template class:

//Primary template
template<typename T> struct ClassOf {};

//Thanks T.C for suggesting leaving out the funtion /^argument
template<typename Return, typename Class>
struct ClassOf<Return (Class::*)>{   using type = Class;    };

//An alias
template< typename T> using ClassOf_t = typename ClassOf<T>::type;

This implies:

struct A { int method() { return 0; } };
auto fn = &A::method;

We can get the class as:

ClassOf_t<decltype(fn)> a;

Full example here .

+2
source

Source: https://habr.com/ru/post/1669450/


All Articles