-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic.cpp
More file actions
62 lines (51 loc) · 1.77 KB
/
Copy pathbasic.cpp
File metadata and controls
62 lines (51 loc) · 1.77 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
#include <structural_interface.hpp>
#include <vector>
#include <print>
// interface
struct Shape {
std::string name; // field member
float area() const; // function member
};
// unified function that accepts any type satisfying the Shape interface
float area(const si::satisfies<Shape> auto& shape) {
return shape.area();
}
// custom types that satisfy the Shape interface
struct Circle {
std::string name;
float radius{ 0.0f };
float area() const {
return 3.14159f * radius * radius;
}
};
struct Rectangle {
std::string name;
float width{ 0.0f };
float height{ 0.0f };
float area() const {
return width * height;
}
};
int main() {
Circle circle{ "Circle", 5.0f };
std::println("Circle area: {}", area(circle)); // static dispatch
std::vector<si::existential<Shape>> shapes{ Circle{ "Circle", 3.0f }, Rectangle{ "Rectangle", 4.0f, 6.0f } };
for (const auto& shape : shapes) {
std::println("Shape {} area: {}", *(shape.name), shape.area()); // dynamic dispatch
}
*(shapes[0].name) = "Updated Circle"; // modify field
std::println("Updated shape name: {}", *(shapes[0].name));
if (si::is<Circle>(shapes[0])) {
Circle& concrete = si::get<Circle>(shapes[0]);
std::println("Concrete type: {}, radius: {}", concrete.name, concrete.radius);
}
const auto& const_shape = shapes[0];
const Circle& const_concrete = si::get<Circle>(const_shape);
std::println("Const view: {}", const_concrete.name);
Circle borrowed_circle{ "Borrowed Circle", 2.0f };
si::existential_ref<Shape> reference = borrowed_circle;
if (si::is<Circle>(reference)) {
si::get<Circle>(reference).radius = 3.0f;
}
std::println("Borrowed shape area: {}", borrowed_circle.area());
}