C++11 decltype of member

C++11 decltype of member

本文关键字:member of decltype C++11      更新时间:2023-10-16

为什么我不能这样做:

class Foo {
  void fn();
  using fn_t = decltype(fn); //call to non-static member function without an object argument
};

但我可以做

class Foo {
  static void fn();
  using fn_t = decltype(fn);
};

此SO帖子声称:

在未赋值的操作数(decltype、sizeof、noexcept等操作数)中,您可以命名成员函数之外的非静态数据成员

fn是表示非静态成员函数的有效id表达式。§5.1.1【expr.prim.general】/p13(省略脚注):

表示非静态数据成员或非静态的id表达式只能使用类的成员函数:

  • 作为类成员访问(5.2.5)的一部分,其中对象表达式引用成员的类或从该类派生的类类,或
  • 形成指向成员(5.3.1)的指针,或
  • 如果id表达式表示非静态数据成员,并且它出现在未赋值的操作数中

§7.1.6.2[dcl.类型.简单]/p4:

decltype说明符的操作数是未赋值的操作数(第5条)。

由于decltype不是少数可以使用表示非静态成员函数的id表达式的上下文之一,因此程序格式不正确。