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

C++20中返回类型与比较类别不同的默认三路比较运算符编译报错问题咨询

C++20中返回类型与比较类别不同的默认三路比较运算符编译报错问题咨询

我最近在研究C++20的默认三路比较运算符时遇到了一个困惑,想跟大家请教一下。

根据cppreference的文档说明,我们可以定义返回类型不是比较类别类型的默认三路比较运算符:

如果a <=> b的重载解析得到一个可用的候选,且该候选的结果可以通过static_cast显式转换为T,那么合成的比较表达式就是static_cast<T>(a <=> b)。

不过,我写的下面这段代码却无法正常编译:

#include <iostream>

struct AA
{
    int a;

    int operator<=> (const AA &other) const
    {
        if (a < other.a)
            return -7;
        else if (a > other.a)
            return 5;
        else
            return 0;
    }
};

struct BB
{
    AA b;

    int operator<=> (const BB &other) const = default;
};

int main ()
{
    BB b1{4}, b2{6};
    std::cout << (b1 <=> b2);
}

按照文档的描述,b1 <=> b2的结果应该是static_cast<int>(b1.b <=> b2.b),但编译器直接报了错:

error: use of deleted function ‘constexpr int BB::operator<=>(const BB&) const’
note: ‘constexpr int BB::operator<=>(const BB&) const’ is implicitly deleted because the default definition would be ill-formed
error: invalid ‘static_cast’ from type ‘const std::strong_ordering’ to type ‘int’

看起来文档的说明好像不够完整?还是我哪里理解错了呢?

备注:内容来源于stack exchange,提问作者lzv

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 18:29:49