如何从指针到方法获取类(对象类型)

时间:2017-02-11 11:26:04

标签: c++ c++14 metaprogramming

我有一个指向该方法的指针:

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

我可以通过std :: result_of获取返回类型,但是如何从 fn 获取方法的类所有者?

2 个答案:

答案 0 :(得分:3)

试试这个:

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

答案 1 :(得分:3)

您可以使用 class-template-specialization 匹配它:

//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;

因此给出:

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

我们可以检索类:

ClassOf_t<decltype(fn)> a;

完整示例Here