value.hh (1881B)
1 #ifndef value_hh_INCLUDED 2 #define value_hh_INCLUDED 3 4 #include "hash_map.hh" 5 #include "meta.hh" 6 #include "unique_ptr.hh" 7 8 #include <type_traits> 9 #include <typeinfo> 10 11 namespace Kakoune 12 { 13 14 struct bad_value_cast {}; 15 16 struct Value 17 { 18 Value() = default; 19 20 template<typename T> requires (not std::is_same_v<Value, T>) 21 Value(T&& val) 22 : m_value{new Model<std::remove_cvref_t<T>>{std::forward<T>(val)}} {} 23 24 template<typename T> 25 Value(Meta::Type<T>, auto&&... args) : 26 m_value(new Model<T>(std::forward<decltype(args)>(args)...)) {} 27 28 Value(const Value& val) = delete; 29 Value(Value&&) = default; 30 31 Value& operator=(const Value& val) = delete; 32 Value& operator=(Value&& val) = default; 33 34 explicit operator bool() const { return (bool)m_value; } 35 36 template<typename T> 37 bool is_a() const 38 { 39 return m_value and m_value->type() == typeid(T); 40 } 41 42 template<typename T> 43 T& as() 44 { 45 if (not is_a<T>()) 46 throw bad_value_cast{}; 47 return static_cast<Model<T>*>(m_value.get())->m_content; 48 } 49 50 template<typename T> 51 const T& as() const 52 { 53 return const_cast<Value*>(this)->as<T>(); 54 } 55 56 private: 57 struct Concept 58 { 59 virtual ~Concept() = default; 60 virtual const std::type_info& type() const = 0; 61 }; 62 63 template<typename T> 64 struct Model : public Concept, public UseMemoryDomain<MemoryDomain::Values> 65 { 66 Model(auto&&... args) : m_content(std::forward<decltype(args)>(args)...) {} 67 const std::type_info& type() const override { return typeid(T); } 68 69 T m_content; 70 }; 71 72 UniquePtr<Concept> m_value; 73 }; 74 75 enum class ValueId : int {}; 76 77 inline ValueId get_free_value_id() 78 { 79 static int next = 0; 80 return (ValueId)(next++); 81 } 82 83 using ValueMap = HashMap<ValueId, Value, MemoryDomain::Values>; 84 85 } 86 87 #endif // value_hh_INCLUDED