Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Three-way comparison (spaceship operator)

Use case

Auto-generate all comparison operators.

Explanation

<=> with = default generates all comparison operators from member-wise comparison (comparing each member in order, one by one).

Code

#include <compare>
#include <cstdint>
#include <iostream>

struct Symbol {
  uint64_t addr;
  const char *name;

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

int main() {
  Symbol main{0x10001000, "_main"};
  Symbol helper{0x10002000, "_helper"};

  std::cout << std::boolalpha;
  std::cout << "main < helper: " << (main < helper) << "\n";
  std::cout << "main == helper: " << (main == helper) << "\n";

  return 0;
}

View on GitHub.

Output

$ ./src/c++20/build/three-way-comparison
main < helper: true
main == helper: false