Master the cutting-edge features of C++20: concepts, ranges, and coroutines.
The future of C++ programming is here.
#include <concepts>template
T double_it(T value) {
return value * 2;
}
// Only works with integral types!
double_it(5); // OK
// double_it(3.14); // Error! template
concept Printable = requires(T t) {
{ std::cout << t } -> std::same_as;
};
template
void print(T value) {
std::cout << value << std::endl;
} template
requires std::integral || std::floating_point
T add(T a, T b) {
return a + b;
} void process(std::integral auto value) {
cout << "Integer: " << value << endl;
}Doubled: 10
Sum: 15
Printed: Hello Concepts!
concept Name = requires(T t) { ... };template<std::integral T>requires std::integral<T>std::integral auto xReview feedback below
#include <ranges>namespace views = std::views;
vector nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Filter even numbers
auto evens = nums | views::filter([](int n) {
return n % 2 == 0;
});
// Output: 2 4 6 8 10 auto squared = nums | views::transform([](int n) {
return n * n;
});
// Output: 1 4 9 16 25 ...auto result = nums
| views::filter([](int n) { return n % 2 == 0; })
| views::transform([](int n) { return n * n; })
| views::take(3);
// Output: 4 16 36views::iota(1, 10) // 1,2,3,...,9
views::take(5) // First 5 elements
views::drop(3) // Skip first 3
views::reverse // Reverse orderEvens: 2 4 6 8 10
Squared: 1 4 9 16 25
First 3 even squares: 4 16 36
Range 1-5: 1 2 3 4 5
namespace views = std::views;nums | views::filter(pred)nums | views::transform(func)x | view1 | view2 | view3Review feedback below
<=>) - three-way comparison that automatically generates all comparison operators.#include <compare>int a = 5, b = 10;
auto result = a <=> b;
// result < 0 means a < b
// result == 0 means a == b
// result > 0 means a > bstruct Point {
int x, y;
auto operator<=>(const Point&) const = default;
// Automatically generates: <, >, <=, >=, ==, !=
};
Point p1{1, 2}, p2{3, 4};
if (p1 < p2) cout << "p1 is less" << endl;struct Version {
int major, minor, patch;
auto operator<=>(const Version& other) const {
if (auto cmp = major <=> other.major; cmp != 0)
return cmp;
if (auto cmp = minor <=> other.minor; cmp != 0)
return cmp;
return patch <=> other.patch;
}
bool operator==(const Version&) const = default;
};std::strong_ordering // Total order (int, string)
std::weak_ordering // Equivalence (case-insensitive)
std::partial_ordering // May be unordered (float NaN)5 <=> 10: less
Point{1,2} < Point{3,4}: true
Version 1.2.3 < 2.0.0: true
All comparisons generated!
auto operator<=>(const T&) const = default;auto r = a <=> b;if (r < 0), if (r == 0), if (r > 0)Review feedback below