【发布时间】:2020-06-08 17:24:07
【问题描述】:
考虑这个有效的 C++17 示例:
struct A {
bool operator==(const A&);
};
int main() {
return A{} == A{};
}
当compiled in clang with -std=c++20 it gives:
<source>:7:15: warning: ISO C++20 considers use of overloaded operator '==' (with operand types 'A' and 'A') to be ambiguous despite there being a unique best viable function [-Wambiguous-reversed-operator]
return A{} == A{};
~~~ ^ ~~~
<source>:2:9: note: ambiguity is between a regular call to this operator and a call with the argument order reversed
bool operator==(const A&);
这个警告是否意味着 C++20 不允许使用典型的比较运算符来比较两个相同类型的对象?什么是正确的选择?这种情况在未来的草稿中是否会发生变化?
【问题讨论】:
-
我将把细节留给语言律师,但创建函数
const应该会让警告消失。我认为警告存在,因为您临时调用operator==。 -
@aep 添加
const确实会消除警告,但删除临时(A a, b; a == b)不会。谢谢,我想它一定与==的一侧是 const 而不是另一侧有关。 -
C++20 没有更多的变化(除了那些仍在上次会议上为该版本合并的变化)。
-
我发誓,我喜欢关注 "use non-member overloads" guideline 的一半原因是很容易忘记声明成员函数本身
const,非成员函数只需要记住声明参数const.