Is there a way to determine a return type of a member function pointer?
Code sample:
///// my library
void my_func(auto mptr) { // have to use `auto`
// some logic based on a return type of mptr: int, string, A, etc.
}
///// client code
struct A {
int foo();
std::string bar(int);
};
class B{
public:
A func(int, double);
};
// ... and many other classes
my_func(&A::foo);
my_func(&A::bar);
my_func(&B::func);
// ... many other calls of my_func()
I need to "fill in" my_func()
.
Edit:
I can't use std::result_of
/std::invoke_result
as I don't know the full list of parameters of mptr
. It's not important with which params a method is supposed to be called as I'm not calling it. I would like to avoid creating an object of base class of mptr
even if I'm able to determine it (using declval
is ok).
You can use partial template specialization to determine the return type of mptr
:
template <typename T>
struct ReturnType;
template <typename Object, typename Return, typename... Args>
struct ReturnType<Return (Object::*)(Args...)>
{
using Type = Return;
};
void my_func(auto mptr) {
typename ReturnType<decltype(mptr)>::Type obj;
}