forked from BowenFu/matchit.cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatching-Polymorphic-Types.cpp
More file actions
71 lines (64 loc) · 1.07 KB
/
Matching-Polymorphic-Types.cpp
File metadata and controls
71 lines (64 loc) · 1.07 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
#include "matchit.h"
#include <iostream>
#include <tuple>
struct Shape
{
virtual ~Shape() = default;
};
struct Circle : Shape
{
int radius;
};
struct Rectangle : Shape
{
int width, height;
};
template <size_t I>
constexpr auto &get(Circle const &c)
{
if constexpr (I == 0)
{
return c.radius;
}
}
template <size_t I>
constexpr auto &get(Rectangle const &r)
{
if constexpr (I == 0)
{
return r.width;
}
else if constexpr (I == 1)
{
return r.height;
}
}
namespace std
{
template <>
class tuple_size<Circle> : public std::integral_constant<size_t, 1>
{
};
template <>
class tuple_size<Rectangle> : public std::integral_constant<size_t, 2>
{
};
} // namespace std
double get_area(const Shape &shape)
{
using namespace matchit;
Id<int> r, w, h;
return match(shape)(
// clang-format off
pattern | as<Circle>(ds(r)) = 3.14 * r * r,
pattern | as<Rectangle>(ds(w, h)) = w * h
// clang-format on
);
}
int32_t main()
{
auto c = Circle{};
c.radius = 5;
std::cout << get_area(c) << std::endl;
return 0;
}