如何将 decltype 与成员函数一起使用

How to use decltype with member functions

我试图在 Visual Studio 2012 年的成员函数上使用 decltype。我偶然发现了一个特性,我想知道这是故意的还是编译器错误。考虑一下(只是一个代码片段,无意表明我的观点):

struct Test { int f() {return 0;} } T;
std::integral_constant<decltype(T.f()), 5>;
std::integral_constant<decltype(&Test::f), 5>; // error C2440

第二行编译时,第三行给出错误 C2440: 'specialization' : cannot convert from 'int' to 'int (__thiscall Test::*)(void)'

如何在对函数的实例化调用上 decltype 产生它的 return 类型(这是我所期待的),但是在没有任何成员参与的情况下尝试做同样的事情会产生一个成员函数指针?如果这是预期的行为,其背后的原因是什么?我如何表示我正在请求 return 类型的成员函数,而实际上手头没有实例?当然我可以用肮脏的方式来做:

std::integral_constant<decltype(((Test*)nullptr)->f()), 5>;

但毫无疑问,这非常非常丑陋,应该有一种干净、直接的 C++ 方式来表达它。

&Test::f没有调用成员函数Test::f。相反,它 takes the address of the member function and results in a pointer to member function,属于 int (Test::*)().

类型

为了做你想做的事,你应该使用std::declval。正确的语法是

std::integral_constant<decltype(std::declval<Test>().f()), 5>