You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何在两个派生类中使用Parent::operator<=>仅GCC 12编译报错?

为什么这段C++20代码在GCC 12编译失败但Clang 14可以?

代码示例

#include<compare>
struct Parent {
    int val;
    auto operator<=>(const Parent&) const = default;
};

struct Child1: public Parent {
    using Parent::operator<=>>;
};

struct Child2: public Parent {
    using Parent::operator<=>>;
};
int main()
{
}

编译情况

  • 可通过命令 clang++-14 -std=c++20 main.cpp 正常编译
  • 执行 g++-12 -std=c++20 main.cpp 时编译失败,报错信息如下:
main.cpp:4:10: error: comparison operator ‘bool Parent::operator==(const Parent&) const’ defaulted after its first declaration
    4 |     auto operator<=>(const Parent&) const = default;
      |          ^~~~~~~~
main.cpp:4:10: note: ‘bool Parent::operator==(const Parent&) const’ previously declared here

原因分析

这是GCC 12对C++20标准中比较运算符继承规则的实现缺陷:

  • 根据C++20标准,当类默认定义了operator<=>时,编译器会隐式生成对应的operator==(前提是类没有显式声明operator==)。
  • 但GCC 12在处理子类通过using声明引入父类的operator<=>时,错误地将父类隐式生成的operator==判定为“重复默认声明”,从而抛出编译错误。
  • Clang的实现则正确遵循了标准规则,没有触发该错误。

该问题已在GCC 13及后续版本中被修复,升级编译器版本即可解决。

内容的提问来源于stack exchange,提问作者phinz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 16:07:49