The Spaceship Operator: – Cloudywizzard

The Spaceship Operator: <=>

C++20 introduces the “Three-Way Comparison Operator” also known as the spaceship operator. A simple example


int main()
    int value{};
    std::cout << std::format("Please enter an integer: );
    std::cin >> value;

    std::strong_ordering result{value <=> 0};
    if (is_lt(result))
              std::cout << std::format("less") << std::endl;
    if (is_gt(result))
              std::cout << std::format("greater") << std::endl;
              std::cout << std::format("equal") << std::endl;

the std::strong_ordering is only available for integral types, for floating-point values there is the std::partial_ordering (less, greater, equivalent and unordered).

For your own defined types there is also the std::weak_ordering (less, greater, equivalent)

Leave a Comment

Het e-mailadres wordt niet gepubliceerd. Vereiste velden zijn gemarkeerd met *

Deze website gebruikt Akismet om spam te verminderen. Bekijk hoe je reactie-gegevens worden verwerkt.