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
相关产品推荐
相关产品推荐

