Home > Blockchain >  Is there a way to get the function type of a pointer to a member function?
Is there a way to get the function type of a pointer to a member function?

Time:12-15

If you have a pointer to a member function like so:

struct Foo {  void func() {}  };

void(Foo::*funcPtr)() = &Foo::func;

Is there a way to get the type of the function, with the Foo:: removed?

I.e.,

void(Foo::*)() -> void(*)()

int(Foo::*)(int, double, float) -> int(*)(int, double, float)

You get the idea.

The goal is to make std::function accept a functor like this:

struct Functor { void operator()(...){} }

Functor f;
std::function< magic_get_function_type< decltype(Functor::operator()) >::type > stdfunc{f};

Is it possible?

CodePudding user response:

To answer your question, it is possible with a simple template:

template <typename Return, typename Class, typename... Args>
Return(*GetSig(Return(Class::*)(Args...)))(Args...);

This defines a function called GetSig that takes as parameter a member function pointer and essentially extracts the Return type and the Args... and returns it as a non-member function pointer.

Example usage:

class C;
int main() {
    using FuncType = int(C::*)(double, float);
    FuncType member_pointer;
    decltype(GetSigType(member_pointer)) new_pointer;
    // new_pointer is now of type int(*)(double, float) instead of
    // int(C::*)(double, float)
}
  • Related