Search code examples
c++c++14metaprogramming

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


I have a pointer to the method:

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

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


Solution

  • Try this:

    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