如何对成员函数使用decltype

How to use decltype with member functions

本文关键字:decltype 函数 成员      更新时间:2023-10-16

我试图在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':不能从'int'转换为'int (__thiscall Test::*)(void)'

如何对一个函数的实例化调用的decltype产生其返回类型(这是我所期望的),然而,试图做同样的没有任何成员涉及产生成员函数指针?如果这是预期的行为,其背后的原因是什么?在没有实际实例的情况下,我如何表示我正在请求成员函数的返回类型?当然,我也可以用不正规的方法:

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

但是毫无疑问,这是非常非常丑陋的,应该有一个干净,直接的c++方式来表达它

&Test::f不调用成员函数Test::f。相反,它接受成员函数的地址,并得到一个指向成员函数的指针,该指针的类型为int (Test::*)()

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

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