这是C++20中的标准行为吗?我在这里找不到任何关于它的东西。
我刚刚在Clang和Visual上都试过了,它可以工作,它不会给我任何错误或警告。我还与调试器检查是否正在调用operator==,它是否调用了!C++20现在允许在operator!=出现时自动生成operator==吗?它默认为一个正常的!(a == b)吗?如果是这样的话,那对C++来说就太棒了!
发布于 2020-09-29 14:30:02
!=自动生成自==in C++20?这是C++20中的标准行为吗?
是。operator!=是由operator==在C++20中自动生成的。
此外,如果定义operator<=>,将生成所有四个关系运算符,如果将operator<=>定义为默认值,则生成所有比较运算符。
在大多数情况下,你想做的事情是:
struct example
{
std::string a;
int b;
auto operator<=>(const example&) const = default;
};发布于 2020-09-30 17:22:50
在较早的C++版本中,您可以使用CRTP (原则)。
其思想是有一个模板库,模板参数是派生类:
template <typename Derived>
class Comparable {
public:
friend constexpr auto operator!=(const Derived &a, const Derived &b) noexcept { return !(a == b); }
friend constexpr auto operator<=(const Derived &a, const Derived &b) noexcept { return !(b < a); }
friend constexpr auto operator>(const Derived &a, const Derived &b) noexcept { return b < a; }
friend constexpr auto operator>=(const Derived &a, const Derived &b) noexcept { return !(a < b); }
};所以,你可以这样使用它:
struct Example : Comparable<Example> {
friend bool operator==(const Example &a, const Example &b);
friend bool operator<(const Example &a, const Example &b);
};如果只声明==运算符,则将自动生成!=,如果同时提供<和==,则将定义所有运算符:)
https://stackoverflow.com/questions/64121390
复制相似问题