use*_*770 5 c++ metaprogramming c++14
我有一个方法的指针:
struct A { int method() { return 0; } };
auto fn = &A::method;
Run Code Online (Sandbox Code Playgroud)
我能获得通过的std ::的result_of返回类型,但我怎样才能从中获取FN方法的类老板?
您可以使用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;
Run Code Online (Sandbox Code Playgroud)
因此给出:
struct A { int method() { return 0; } };
auto fn = &A::method;
Run Code Online (Sandbox Code Playgroud)
我们可以像这样检索类:
ClassOf_t<decltype(fn)> a;
Run Code Online (Sandbox Code Playgroud)
完整示例在这里。
尝试这个:
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
Run Code Online (Sandbox Code Playgroud)