Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 987
user2427770 Avatar asked Feb 11 '17 11:02

user2427770


People also ask

How do I get the type of an object in C++?

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.

How do you access a pointer to an object?

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.

How do you dereference pointers to class objects?

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 .

What is a pointer to object type?

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.


2 Answers

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
like image 113
The Techel Avatar answered Oct 01 '22 14:10

The Techel


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.

like image 35
WhiZTiM Avatar answered Oct 01 '22 14:10

WhiZTiM