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

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

代码示例:

///// 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()

我需要“填写” my_func()

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

回答

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

现场演示


以上是如何获取成员函数指针的返回类型的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>