Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

c++20 - Why do we need the spaceship <=> operator in C++?

Why do we need such an operator in C++ and how is it useful in modern C++ programming? Any real world code examples where this can be applied will help.

This question is geared to understand the practical application in real world without reading wordy proposal from Herb Sutter. No offense to the proposal though.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'll give you three points of motivation, just off the top of my head:

  1. It's the common generalization of all other comparison operator (for totally-ordered domains): >, >=, ==, <=, < . Using <=> (spaceship), you can implement each of these other operations in a completely generic way.
  2. For strings, it's equivalent to the good old strcmp() function from the C standard library. So - useful for lexicographic order checks, such as data in vectors or lists or other ordered containers.
  3. For integral numbers, it's what the hardware does anyway: On x86 or x86_64 Comparing a and b (CMP RAX, RBX) is basically like subtracting (SUB RAX, RBX) except that RAX doesn't actually change, only the flags are affected, so you can use "jump on equal/not equal/greater than/lesser than/etc." (JE/JNE/JGT/JLT etc.) as the next instruction. CMP should be thought of as a "spaceship compare".

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...