๐ Modern C++ Features: Comparison & Coroutines
Imagine youโre a judge at a talent show. Before C++20, you had to write separate rules for โgreater than,โ โless than,โ and โequal to.โ Now, with ONE magic wand, you can decide ALL comparisons at once!
๐ฏ The Big Picture
Think of comparing things like sorting your toy box:
- Old Way: Check each toy one by one with many rules
- New Way: Wave a magic wand and instantly know the order!
That magic wand? Itโs called the Spaceship Operator (<=>).
๐ Three-Way Comparison
What Is It?
Imagine asking: โIs Apple bigger, smaller, or the same as Banana?โ
Instead of asking THREE separate questions:
- Is Apple > Banana?
- Is Apple < Banana?
- Is Apple == Banana?
You ask ONE question and get ONE answer that tells you everything!
The Magic Answer Types
// Three possible answers:
// negative = "less than"
// zero = "equal"
// positive = "greater than"
Real Life Example:
- You have 5 candies, friend has 7
- Three-way comparison says: โYou have LESSโ
- One check tells the whole story!
Why This Matters
// OLD WAY - So much typing! ๐ซ
bool operator<(const Toy& a, const Toy& b);
bool operator>(const Toy& a, const Toy& b);
bool operator==(const Toy& a, const Toy& b);
bool operator<=(const Toy& a, const Toy& b);
bool operator>=(const Toy& a, const Toy& b);
bool operator!=(const Toy& a, const Toy& b);
// NEW WAY - Just ONE line! ๐
auto operator<=>(const Toy& a,
const Toy& b) = default;
๐ธ The Spaceship Operator <=>
Why โSpaceshipโ?
Look at it sideways: <=> looks like a UFO! ๐ธ
<=>
/ \
๐ฝ ๐ฝ
How It Works
#include <compare>
int a = 5;
int b = 10;
auto result = a <=> b;
// result is "less" because 5 < 10
The Three Categories
Think of comparing different things:
graph TD A["Comparison Types"] --> B["Strong Ordering"] A --> C["Weak Ordering"] A --> D["Partial Ordering"] B --> E["1 < 2 < 3<br/>Clear winner!"] C --> F["Case-insensitive<br/>A == a"] D --> G["NaN exists<br/>Some can&#39;t compare"]
1. Strong Ordering ๐ช
Like numbered jerseys - everyone has a unique spot!
// Integers have STRONG ordering
int x = 5, y = 10;
auto r = x <=> y;
// r is std::strong_ordering::less
2. Weak Ordering ๐ค
Like sorting by height - ties are allowed!
// Case-insensitive strings
// "Hello" and "HELLO" are equivalent
// but not identical
3. Partial Ordering ๐คท
Like comparing apples and oranges - sometimes you canโt!
// Floating point has PARTIAL ordering
// because NaN (Not a Number) can't
// be compared to anything!
double nan = std::nan("");
auto r = nan <=> 1.0;
// r is std::partial_ordering::unordered
Your Class Gets Superpowers!
struct Student {
std::string name;
int score;
// ONE line gives you ALL comparisons!
auto operator<=>(const Student&)
const = default;
};
// Now you can do:
Student alice{"Alice", 95};
Student bob{"Bob", 87};
if (alice > bob) // Works!
if (alice < bob) // Works!
if (alice == bob) // Works!
// ALL SIX operators work automatically!
๐ Coroutines: Functions That Can Pause!
The Story
Imagine reading a REALLY long book:
Normal Function (Regular Reading):
- Start at page 1
- MUST finish the whole book
- Canโt stop until THE END
- Others wait forever! ๐ด
Coroutine (Smart Reading):
- Read chapter 1โฆ PAUSE โธ๏ธ
- Go play outside! ๐ฎ
- Come back, read chapter 2โฆ PAUSE โธ๏ธ
- Help mom cook! ๐ณ
- Continue where you left off!
The Three Magic Words
graph TD A["Coroutine Keywords"] --> B["co_await"] A --> C["co_yield"] A --> D["co_return"] B --> E["Wait for something"] C --> F["Give value & pause"] D --> G["Finish & give result"]
1. co_await - โPlease Waitโ โณ
// Like waiting for your pizza delivery
Task<Pizza> orderDinner() {
Pizza myPizza = co_await orderPizza();
// Pauses here until pizza arrives!
// Other code can run while waiting
return myPizza;
}
Real Life:
- You order pizza online
- Instead of staring at the doorโฆ
- You play games while waiting!
- Door bell rings โ get pizza โ continue!
2. co_yield - โHereโs One!โ ๐
// Like a candy dispenser
Generator<int> countTo(int n) {
for (int i = 1; i <= n; i++) {
co_yield i; // Give one number
// Pause until asked for next!
}
}
// Usage:
for (int num : countTo(5)) {
std::cout << num << " ";
}
// Output: 1 2 3 4 5
Real Life:
- Vending machine gives ONE snack at a time
- You take it, eat it
- Come back for another!
- Machine remembers your count!
3. co_return - โIโm Done!โ โ
Task<std::string> greet(std::string name) {
co_return "Hello, " + name + "!";
}
Why Coroutines Are Amazing
BEFORE (Blocking):
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Download File... โ
โ โโโโโโโโโโโโโโโโโโโโ 60% โ
โ โ
โ [Everything else FROZEN!] โ๏ธโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
AFTER (Coroutines):
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Download: โโโโโโ 30% โ
โ Upload: โโโโโโ 50% โ
โ Process: โโโโโโ 20% โ
โ [All happening together!] ๐โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
A Complete Example
#include <coroutine>
#include <iostream>
// Simple generator
template<typename T>
struct Generator {
struct promise_type {
T value;
Generator get_return_object() {
return Generator{this};
}
std::suspend_always initial_suspend() {
return {};
}
std::suspend_always final_suspend()
noexcept { return {}; }
std::suspend_always yield_value(T v) {
value = v;
return {};
}
void return_void() {}
void unhandled_exception() {}
};
// Handle & iterator code...
promise_type* promise;
Generator(promise_type* p) : promise(p) {}
};
// Use it!
Generator<int> fibonacci(int count) {
int a = 0, b = 1;
for (int i = 0; i < count; i++) {
co_yield a;
int next = a + b;
a = b;
b = next;
}
}
๐ฎ Quick Summary
| Feature | What It Does | Likeโฆ |
|---|---|---|
<=> |
All comparisons in ONE | Magic sorting hat ๐ฉ |
co_await |
Pause & wait | Ordering pizza ๐ |
co_yield |
Give value & pause | Vending machine ๐ฌ |
co_return |
Finish coroutine | โThe Endโ ๐ |
๐ก Remember This!
๐ธ Spaceship Operator:
One operator to rule them all!
<=> gives you <, >, ==, !=, <=, >= for FREE!
๐ Coroutines:
Functions that can PAUSE and RESUME!
Like a game you can save and continue later!
๐ You Did It!
You just learned:
- โ Three-Way Comparison (one check tells all!)
- โ
Spaceship Operator (the
<=>superhero) - โ Coroutines (pausable functions)
These features make C++ code:
- Shorter (less typing!)
- Smarter (better performance!)
- Simpler (easier to understand!)
Now go build something amazing! ๐
