【发布时间】:2021-12-27 14:35:44
【问题描述】:
这段代码sn-p
#include <stdlib.h>
struct Base { };
template<typename T>
inline bool operator==(const T&, const Base&)
{
return true;
}
template<typename T>
inline bool operator!=(const T& lhs, const Base& rhs)
{
return !(lhs == rhs);
}
struct A : public Base
{
bool operator==(const A&) const { return true; }
};
struct A_1 final : public A { };
int main()
{
const A a;
const A_1 a_1;
if (a_1 != a) {}
return EXIT_SUCCESS;
}
在 C++17 (Visual Studio 2022) 中编译没有错误。 (有关更详细的示例,请参阅 C++17 operator==() and operator!=() code fails with C++20;请注意在这种情况下代码编译。)
尝试使用 C++20 构建相同的代码会产生三个编译器错误:
error C2666: 'operator !=': 3 overloads have similar conversions
message : could be 'bool A::operator ==(const A &) const' [rewritten expression '!(x == y)']
message : or 'bool A::operator ==(const A &) const' [synthesized expression '!(y == x)']
message : or 'bool operator !=<A_1>(const T &,const Base &)'
是的,我 understand 认为 C++20 将合成 operator!= 等......但是现有的 C++17 代码不应该仍然用 C++20 编译吗?我该如何解决问题,以使 same 代码同时使用 C++17 和 C++20 编译 并且 生成相同的结果?
对派生类进行更改可能很困难,因为该代码可能在其他地方(这实际上是库代码); 非常更愿意更改Base。
【问题讨论】:
-
c++20 如果不存在,则从
operator ==生成operator !=。所以也提供所有operator !=。 -
"但现有的 C++17 代码不应该仍然使用 C++20 编译" - 不。 C++20 引入了操作数重新排序。这是一个已知的潜在重大变化。
-
这个问题和你之前的问题C++17 operator==() and operator!=() code fails with C++20有什么不同?
-
@CrisLuengo "...注意在这种情况下代码编译。"
-
代码略有不同,但问题是一样的,我想。
标签: c++ c++17 c++20 spaceship-operator