c++ - 'override' 限定符与尾随返回类型一起去哪里?

标签 c++ c++11

C++11 具有新的 override 限定符,可应用于成员函数以断言它们覆盖基类中的虚函数。 C++11 还允许尾随返回类型,因此函数可以声明为 auto f() -> return_type。当我结合这两个功能时,我不知道 override 是在 -> 之前还是之后。

例如,假设我们有以下基类:

struct Base {
    virtual auto f () const -> int = 0;
};

派生类的两种可能性是:

struct Derived : public Base {
    virtual auto f () const override -> int { return 0; } // Compiles on g++ 4.7.1
};

struct Derived : public Base {
    virtual auto f () const -> int override { return 0; } // Compiles on clang++ 4.0
};

g++ 4.7.1 编译了第一个版本,但在第二个版本中失败了

test.cpp:6:30: error: expected ';' at end of member declaration
test.cpp:6:34: error: 'override' does not name a type

而 clang++ 4.0 编译第二个,但在第一个失败

test.cpp:6:11: error: 'auto' return without trailing return type
  virtual auto f () const override -> int { return 0; }
          ^
test.cpp:6:3: error: only virtual member functions can be marked 'override'
  virtual auto f () const override -> int { return 0; }
  ^                       ~~~~~~~~
test.cpp:6:35: error: expected ';' at end of declaration list
  virtual auto f () const override -> int { return 0; }

这些编译器中的哪一个实际上根据标准在做正确的事情?

编辑: 正如 Kerrek SB 所说,这是 a bug in gcc (Bugzilla link) .

最佳答案

根据标准,8.4.1,一个函数的declarator包含trailing-return-type,一个类函数定义包含“declarator virt-specifier-seqopt"。第二个,virt-specifier-seq,是 finaloverride 之一,所以它们在 之后尾随返回类型。 (即 Clang 做对了。)

关于c++ - 'override' 限定符与尾随返回类型一起去哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12771005/

相关文章:

c++ - Google 基准测试结果中显示的时间没有意义

c++ - 编译器可以删除具有相同定义的重复 lambda 表达式吗?

c++ - 帮助 : VS2005 Compile *. m 文件

c++ - ServerApplication 看不到具有相对路径的文件

c++ - YouCompleteMe 和 C++ 诊断不当错误

c++ - QCheckBoxes的QComboBox,看不到QCheckBox,只有文本

c++ - 列表初始化是隐式转换吗?

c++ - TBB 分配发出终止信号

C++ - 将对象(如字符串)映射到表中的成员函数的正确方法

sockets - 在ASIO Reactor中使用Lambda的Auto vs Typedef