如何获取成员函数指针的返回类型

Max*_*rov 1 c++ member-function-pointers decltype type-traits

有没有办法确定成员函数指针的返回类型?

代码示例:

///// 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()
Run Code Online (Sandbox Code Playgroud)

我需要“填写” my_func()

编辑:我不能使用std::result_of/std::invoke_result因为我不知道mptr. 应该使用哪些参数调用方法并不重要,因为我没有调用它。我想避免创建基类的对象,mptr即使我能够确定它(使用declval是可以的)。

Mil*_*nek 6

您可以使用部分模板特化来确定 的返回类型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;
}
Run Code Online (Sandbox Code Playgroud)

现场演示