-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathcustomAsPointer.cpp
71 lines (60 loc) · 1.23 KB
/
customAsPointer.cpp
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>
enum class Kind
{
kONE,
kTWO
};
#if __cplusplus > 201703L
#define CPP20_CONSTEXPR constexpr
#else
#define CPP20_CONSTEXPR
#endif
class Num
{
public:
CPP20_CONSTEXPR virtual Kind kind() const = 0;
protected:
~Num() = default;
};
class One : public Num
{
public:
constexpr static auto k = Kind::kONE;
CPP20_CONSTEXPR Kind kind() const override { return k; }
};
class Two : public Num
{
public:
constexpr static auto k = Kind::kTWO;
CPP20_CONSTEXPR Kind kind() const override { return k; }
};
template <Kind k>
constexpr auto kind = matchit::app(&Num::kind, k);
template <typename T>
auto get_if(Num const *num)
{
std::cout << "get_if" << std::endl;
return static_cast<T const *>(num->kind() == T::k ? num : nullptr);
}
constexpr int32_t staticCastAs(Num const &input)
{
using namespace matchit;
return match(input)(
// clang-format off
pattern | as<One>(_) = 1,
pattern | kind<Kind::kTWO> = 2,
pattern | _ = 3
// clang-format on
);
}
#if 0 // fail on gcc, fix me later.
#if __cplusplus > 201703L
static_assert(staticCastAs(One{}) == 1);
#endif
#endif
int32_t main()
{
std::cout << staticCastAs(One{}) << std::endl;
return 0;
}