gpt4 book ai didi

c++ - 三路运算符 <=> 返回带有隐式转换函数的结构体

转载 作者:行者123 更新时间:2023-12-04 11:28:15 27 4
gpt4 key购买 nike

考虑以下无用的代码:

struct S{
constexpr operator int() const { return 0; }
constexpr auto operator<=>(S) const { return *this; }
};

static_assert(S{} <= S{});
Clang 和 MSVC 接受此代码,但 GCC rejects它带有错误消息:
error: no match for 'operator<=' (operand types are 'S' and 'int')
哪个编译器是对的?如何 operator<=合成自 operator<=> ?

最佳答案

来自 [over.match.oper]( 3.4.18 ):

For the relational ([expr.rel]) operators, the rewritten candidates include all non-rewritten candidates for the expression x <=> y.



If a rewritten operator<=> candidate is selected by overload resolution for an operator @, x @ y is interpreted as [...] (x <=> y) @ 0 [...], using the selected rewritten operator<=> candidate. Rewritten candidates for the operator @ are not considered in the context of the resulting expression.


所以对于表达式 S{} <= S{}选定的运算符将为 S::operator<=>(S) const表达式将改写为 (S{} <=> S{}) <= 0 .在重写的表达式中,操作数的类型是 Sint ,其中内置 operator<=(int, int)将被选中。所以最终表达式(在将 S 转换为 int 之后)将导致 0 <= 0 , 即 true .
总之,在这种情况下,Clang 和 MSVC 是正确的,而 GCC 似乎无法解释 (S{} <=> S{}) <= 0作为对内置操作符的调用(注意读取 operand types are 'S' and 'int' 的错误消息)。如果您更改 static_assert 中的条件成为重写的表达式 (S{} <=> S{}) <= 0 ,然后 all three compilers accept it .

关于c++ - 三路运算符 <=> 返回带有隐式转换函数的结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66666894/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com