-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
99 lines (80 loc) · 2.8 KB
/
Copy pathmain.cpp
File metadata and controls
99 lines (80 loc) · 2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <iostream>
#include <string>
#include <vector>
#include <ranges>
#include <format>
#include <expected> // C++23 std::expected
// Global Point type using C++23/26 "deducing this" feature.
// This cannot be placed inside a function (local class)
// because template member functions are not allowed in local classes.
struct Point
{
int x{0};
int y{0};
// C++23/26: "deducing this" syntax
auto move(this Point self, int dx, int dy)
{
self.x += dx;
self.y += dy;
return self;
}
};
std::string make_message()
{
std::string result;
// ------------------------------------------------------------
// C++20: ranges + std::format
// ------------------------------------------------------------
{
std::vector<int> nums = {1, 2, 3, 4, 5};
// Range pipeline: filter even numbers, then square them
auto even_square_view =
nums
| std::views::filter([](int x) { return x % 2 == 0; })
| std::views::transform([](int x) { return x * x; });
int sum = 0;
for (int v : even_square_view)
sum += v;
result += std::format("[C++20] Sum of even squares = {}\n", sum);
}
// ------------------------------------------------------------
// C++23: std::expected + views::join
// ------------------------------------------------------------
{
// Safe division using std::expected
auto safe_div = [](int a, int b) -> std::expected<int, std::string> {
if (b == 0)
return std::unexpected("Division by zero");
return a / b;
};
auto r = safe_div(10, 2);
if (r.has_value())
result += std::format("[C++23] safe_div OK: {}\n", r.value());
else
result += std::format("[C++23] safe_div error: {}\n", r.error());
// Join view to flatten nested containers
std::vector<std::vector<int>> nested = {{1, 2}, {3, 4}};
auto flat = nested | std::views::join;
int s = 0;
for (int v : flat)
s += v;
result += std::format("[C++23] Flattened vector sum = {}\n", s);
}
// ------------------------------------------------------------
// C++26: deducing this + enhanced formatting
// ------------------------------------------------------------
{
Point p{10, 20};
Point q = p.move(5, 7); // Calls deducing-this member function
result += std::format("[C++26] Point move: ({}, {}) -> ({}, {})\n",
p.x, p.y, q.x, q.y);
// Enhanced formatting in C++26 (implementation-dependent)
result += std::format("[C++26] Formatting example: {:.3f}\n", 3.1415926535);
}
return result;
}
int main()
{
std::cout << make_message();
return 0;
}