从成员函数指针获取方法的 return 类型

Get the return type of a method from a member function pointer

我试图声明一个变量,使其类型与我有一个成员函数指针的成员函数的 return 类型相同。

class Widget {
    public:
        std::chrono::milliseconds Foo();
};

例如,给定一个指向Widget::Foo的成员函数指针fn, 我如何声明变量 blah 以便它获得 Widget::Foo 的 return 类型 (std::chrono::milliseconds)?

我从博客 post 中找到了一些有前途的指导,该博客使用 <type_traits> 中的 result_ofdecltype,但我似乎无法让它发挥作用.

auto fn = &Widget::Foo;
Widget w;
std::result_of<decltype((w.*fn)())>::type blah;

这种方法对我来说很有意义,但是 VC++ 2013 不喜欢它。

C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xrefwrap(58): error C2064: term does not evaluate to a function taking 0 arguments
      C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xrefwrap(118) : see reference to class template instantiation 'std::_Result_of<_Fty,>' being compiled
      with
      [
          _Fty=std::chrono::milliseconds (__cdecl Widget::* )(void)
      ]
      scratch.cpp(24) : see reference to class template instantiation 'std::result_of<std::chrono::milliseconds (__cdecl Widget::* (void))(void)>' being compiled

我不知道我是不是做错了什么,或者这是否是 VC++ 尚未处理的(或两者!)。我在错误消息中看到的唯一线索是 __cdecl。调用约定不应该是 __thiscall 吗?

decltype((w.*fn)()) blah;

或者

std::result_of<decltype(fn)(Widget)>::type blah;

不知道为什么与

一起使用
std::result_of<decltype(fn)(Widget)>::type blah;

不过我觉得括号里应该是指向Widget的指针。因为the first member parameter is hidden 'this', a pointer to object

std::result_of<decltype(fn)(Widget*)>::type blah;




#include <iostream>
using namespace std;

class Widget
{
public:
    virtual int foo() = 0;
};

int Widget::foo()
{}

int main() {
    // your code goes here
    auto fn = &Widget::foo;
    std::result_of<decltype(fn)(Widget*)>::type blah = 5;
    std::cout << blah;
    return 0;
}

输出:

5

我们也不能创建抽象的对象classes,所以代码不会编译,如果Widget是一个抽象的class而不是它的指针将在括号中

std::result_of<decltype(fn)(Widget)>::type blah = 5;

编译错误:

error: cannot declare parameter to be of abstract type 'Widget'
  std::result_of<decltype(fn)(Widget)>::type blah = 5;//

error: incomplete type 'std::result_of<int (Widget::*(Widget))()>' used in    nested name specifier
  std::result_of<decltype(fn)(Widget)>::type blah = 5;//