1 | #pragma once |
---|
2 | |
---|
3 | #include <exception> |
---|
4 | #include <memory> |
---|
5 | #include <string> |
---|
6 | #include <typeinfo> |
---|
7 | #include <typeindex> |
---|
8 | |
---|
9 | class bad_cast : public std::exception { |
---|
10 | std::string why; |
---|
11 | public: |
---|
12 | bad_cast( const std::type_index& f, const std::type_index& t ) : std::exception() { |
---|
13 | why = std::string{"bad cast of "} + f.name() + " to " + t.name(); |
---|
14 | } |
---|
15 | |
---|
16 | ~bad_cast() override = default; |
---|
17 | |
---|
18 | const char* what() const noexcept override { return why.c_str(); } |
---|
19 | }; |
---|
20 | |
---|
21 | class object { |
---|
22 | public: |
---|
23 | std::type_index get_class() const { return { typeid(*this) }; } |
---|
24 | |
---|
25 | template<typename T> |
---|
26 | T& as() { |
---|
27 | std::type_index from = get_class(), to = { typeid(T) }; |
---|
28 | if ( from != to ) throw bad_cast{ from, to }; |
---|
29 | return reinterpret_cast<T&>(*this); |
---|
30 | } |
---|
31 | |
---|
32 | template<typename T> |
---|
33 | const T& as() const { |
---|
34 | std::type_index from = get_class(), to = { typeid(T) }; |
---|
35 | if ( from != to ) throw bad_cast{ from, to }; |
---|
36 | return reinterpret_cast<const T&>(*this); |
---|
37 | } |
---|
38 | |
---|
39 | virtual std::unique_ptr<object> new_inst() const = 0; |
---|
40 | |
---|
41 | virtual std::unique_ptr<object> new_copy() const = 0; |
---|
42 | |
---|
43 | virtual object& operator= (const object&) = 0; |
---|
44 | |
---|
45 | virtual ~object() = default; |
---|
46 | }; |
---|
47 | |
---|
48 | class integer : public object { |
---|
49 | private: |
---|
50 | int x; |
---|
51 | |
---|
52 | public: |
---|
53 | integer() = default; |
---|
54 | |
---|
55 | integer(int x) : x(x) {} |
---|
56 | |
---|
57 | std::unique_ptr<object> new_inst() const override { return std::make_unique<integer>(); } |
---|
58 | |
---|
59 | std::unique_ptr<object> new_copy() const override { return std::make_unique<integer>(*this); } |
---|
60 | |
---|
61 | integer& operator= (const integer& that) { |
---|
62 | x = that.x; |
---|
63 | return *this; |
---|
64 | } |
---|
65 | |
---|
66 | object& operator= (const object& that) override { |
---|
67 | std::type_index from = that.get_class(), to = get_class(); |
---|
68 | if ( from != to ) throw bad_cast{ from, to }; |
---|
69 | return *this = reinterpret_cast<const integer&>(that); |
---|
70 | } |
---|
71 | |
---|
72 | ~integer() override = default; |
---|
73 | |
---|
74 | integer& operator+= (const integer& that) { |
---|
75 | x += that.x; |
---|
76 | return *this; |
---|
77 | } |
---|
78 | }; |
---|