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?
C++ provides an operator called ' typeid() ' operator for determining the type of object. The typeid() operator is defined as an operator that is used where the dynamic type of a polymorphic object must be known for static type identification.
To access a member function by pointer, we have to declare a pointer to the object and initialize it (by creating the memory at runtime, yes! We can use new keyboard for this). The second step, use arrow operator -> to access the member function using the pointer to the object.
The . * operator is used to dereference pointers to class members. The first operand must be of class type. If the type of the first operand is class type T , or is a class that has been derived from class type T , the second operand must be a pointer to a member of a class type T .
A pointer is a variable that stores the memory address of another variable (or object) as its value. A pointer aims to point to a data type which may be int, character, double, etc. Pointers to objects aim to make a pointer that can access the object, not the variables.
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
You can match it using 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;
Hence given:
struct A { int method() { return 0; } };
auto fn = &A::method;
We can retrieve the class like:
ClassOf_t<decltype(fn)> a;
Full example Here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With