【问题标题】:!= auto generated from == in C++20?!= 在 C++20 中从 == 自动生成?
【发布时间】:2021-01-15 04:04:57
【问题描述】:

这是 C++20 中的标准行为吗?我在 cppreference 中找不到任何关于它的信息。

我刚刚在 Clang 和 Visual Studio 上都进行了尝试,它可以正常工作,并且没有给我任何错误或警告。我还检查了调试器是否正在调用 operator== 并且确实如此!当存在operator== 时,C++20 现在是否允许自动生成operator!=?它是否默认为理智的!(a == b)?如果是这样,那对 C++ 来说太棒了!

【问题讨论】:

  • 它是here。请参阅关系运算符中的最后一点。
  • 问这个问题的通常方式是"Hey! Where are my standard operators!?"(也在this variant中)。
  • @StoryTeller-UnslanderMonica 也许是骗子?
  • @cigien - 也许吧。我不倾向于在任何一个方向上投票。

标签: c++ operator-overloading comparison c++20 comparison-operators


【解决方案1】:

!= 在 C++20 中从 == 自动生成?

这是 C++20 中的标准行为吗?

是的。 operator!= 是在 C++20 中从 operator== 自动生成的。

此外,如果您定义operator<=>,则会生成所有四个关系运算符,如果您将operator<=> 定义为默认值,则会生成所有比较运算符。

在大多数情况下你想做什么:

struct example
{
    std::string a;
    int         b;

    auto operator<=>(const example&) const = default;
};

【讨论】:

  • 我认为所有 6 个运算符都称为关系运算符。
  • @cigien 在数学/英语中,是的。在 C++ 中,否:有 4 个关系运算符和 2 个相等运算符。
  • 嗯,有道理。在 cppreference 上,就在“4 个关系运算符...”的文本上方,它显示“当提供三向比较(例如 std::memcmp 或 std::string::compare)时,所有六个关系运算符都可以可以通过以下方式表达:“。在其中一种情况下必须是拼写错误。
  • @cigien 在某种程度上两者都是正确的,但彼此不一致。
  • 哈哈,哎呀,真不幸。也许我会修复它(或者至少有人应该)。
【解决方案2】:

在旧 C++ 版本中您可以做的是使用 CRTP(Curriously Recuring Template 原则)。

思路是要有一个模板库,模板参数是Derived类:

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);
};

如果您只声明== 运算符,您将自动生成!=,如果您同时提供&lt;==,所有运算符都将被定义:)

【讨论】:

    猜你喜欢
    • 2012-04-24
    • 1970-01-01
    • 2019-10-19
    • 2017-04-22
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    • 2012-11-27
    • 2010-11-27
    相关资源
    最近更新 更多