如何对成员函数使用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':不能从'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>
相关文章:
- 如何从"decltype()"获取函数参数的数量<funtion>?
- 非静态成员函数的 decltype 格式不正确吗?
- 是否可以使用单个定义定义函数的常量和常规版本?(使用模板,自动,decltype等)
- 使用具有默认参数的函数模板进行 decltype 会使结果混乱(一个有趣的问题或 gcc 的错误)
- 指向具有 decltype 的函数的指针向量
- 是否可以获取将根据 ADL 调用的函数的 decltype?
- 元函数使用 decltype 返回元素类型
- 使用 decltype(this) 获取函数引用
- 如何使用非尾随 decltype 返回类型定义行外类模板成员函数
- 在非常量成员函数中,为什么点这个非常量,而 decltype 指针这是常量
- 静态断言 std::array 的大小,其类型是使用 decltype 从成员函数的返回值中获取的
- 使用自动>decltype方法显式实例化函数
- 模板函数的返回类型未知,使用 decltype 时代码重复
- 使用 decltype 显式析构函数调用
- GCC 中的编译器错误,但在将 decltype 与具有尾随返回类型语法的模板化成员函数一起使用时没有 clang
- 类内定义函数的 decltype 推导结果
- 为什么 decltype 不能使用重载函数?
- 如何将 decltype 应用于运算符 [] 声明中的成员函数
- 是否允许在 std::d eclval 上使用 decltype<T>(函数本身,而不是调用它的结果)?
- c++ 11 -使用decltype函数指针有什么问题?