[英]Overriding spaceship operator when parent class does not define spaceship operator for itself
The following code is treated differently by the compilers:编译器对以下代码的处理方式不同:
#include <compare>
struct A;
struct I {
virtual std::strong_ordering operator <=>(const A&) const {
return std::strong_ordering::equal;
}
};
struct A : I {
virtual std::strong_ordering operator <=>(const A&) const = default;
};
Both GCC and MSVC accept it, but not Clang which returns the error: GCC 和 MSVC 都接受它,但 Clang 不接受它返回错误:
warning: explicitly defaulted three-way comparison operator is implicitly deleted [-Wdefaulted-function-deleted]
virtual std::strong_ordering operator <=>(const A&) const = default;
defaulted 'operator<=>' is implicitly deleted because there is no viable three-way comparison function for base class 'I'
error: deleted function 'operator<=>' cannot override a non-deleted function
virtual std::strong_ordering operator <=>(const A&) const = default;
Demo: https://gcc.godbolt.org/z/WGrGTe89z演示: https://gcc.godbolt.org/z/WGrGTe89z
It seems that Clang is the only one right here, since I::operator <=>(const I&) const
is not defined, so A::operator <=>(const A&) const
must be implicitly deleted, and a deleted method cannot override a not deleted method from I
.似乎 Clang 是这里唯一的一个,因为
I::operator <=>(const I&) const
没有定义,所以A::operator <=>(const A&) const
必须被隐式删除,并且是一个删除的方法无法覆盖I
中未删除的方法。 Are the other compilers also within their rights to accept the code?其他编译器是否也有权接受代码?
The other compilers will also reject the code once you write something like A a; a < a;
一旦您编写了
A a; a < a;
A a; a < a;
, which makes me think Clang is rejecting it prematurely. ,这让我觉得 Clang 过早地拒绝了它。 In [class.compare.default] , the standard says:
在[class.compare.default]中,标准说:
A comparison operator function for class C that is defaulted on its first declaration and is not defined as deleted is implicitly defined when it is odr-used or needed for constant evaluation.
用于 class C 的比较运算符 function C 在其第一个声明中默认并且未定义为已删除,当它被使用或需要常量评估时隐式定义。 Name lookups in the defaulted definition of a comparison operator function are performed from a context equivalent to its function-body.
比较运算符 function 的默认定义中的名称查找是从与其函数体等效的上下文中执行的。 A definition of a comparison operator as defaulted that appears in a class shall be the first declaration of that function.
出现在 class 中的默认比较运算符的定义应是该 function 的第一个声明。
Since there is no expression resolving to A::operator<=>(const A&)
in your example, no definition is needed and it should not be rejected, even if the function would always end up being deleted.由于在您的示例中没有解析为
A::operator<=>(const A&)
的表达式,因此不需要定义并且不应拒绝它,即使 function 总是最终被删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.