source: doc/generic_types/evaluation/object.hpp @ b276be5

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since b276be5 was b276be5, checked in by Aaron Moss <a3moss@…>, 7 years ago

Further updates to benchmarks (new C++ virtual benchmark still slightly broken)

  • Property mode set to 100644
File size: 1.8 KB
Line 
1#pragma once
2
3#include <exception>
4#include <memory>
5#include <string>
6#include <typeinfo>
7#include <typeindex>
8
9class bad_cast : public std::exception {
10        std::string why;
11public:
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
21class object {
22public:
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
48class integer : public object {
49private:
50        int x;
51
52public:
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};
Note: See TracBrowser for help on using the repository browser.