X-Git-Url: http://git.tdb.fi/?a=blobdiff_plain;f=source%2Fcore%2Fvariant.h;h=4a0c89cf1a9a4b22661d28e62ba192a06004aabd;hb=4418103963cca2b68fd2dbf6d1d16eeebc8b3c40;hp=f78851f8582710849db54b3b7259042918897a75;hpb=cfc8e0b7b15ea505bd6a6a9599cbc5ce1e316963;p=libs%2Fcore.git diff --git a/source/core/variant.h b/source/core/variant.h index f78851f..4a0c89c 100644 --- a/source/core/variant.h +++ b/source/core/variant.h @@ -1,25 +1,29 @@ -/* $Id$ - -This file is part of libmspcore -Copyright © 2008 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ - #ifndef MSP_CORE_VARIANT_H_ #define MSP_CORE_VARIANT_H_ -#include "except.h" +#include +#include #include "meta.h" namespace Msp { +class type_mismatch: public std::runtime_error +{ +public: + type_mismatch(const std::type_info &, const std::type_info &); + ~type_mismatch() throw() { } +}; + + class Variant { private: struct StoreBase { virtual ~StoreBase() { } - virtual StoreBase *clone() const =0; + + virtual const std::type_info &type_id() const = 0; + virtual StoreBase *clone() const = 0; }; template @@ -28,6 +32,8 @@ private: T data; Store(T d): data(d) { } + + virtual const std::type_info &type_id() const { return typeid(T); } virtual StoreBase *clone() const { return new Store(data); } }; @@ -44,25 +50,39 @@ public: Variant &operator=(const T &v) { delete store; - store=new Store::Type>(v); + store = new Store::Type>(v); return *this; } Variant &operator=(const Variant &v) { delete store; - store=(v.store ? v.store->clone() : 0); + store = (v.store ? v.store->clone() : 0); return *this; } +private: template - T &value() const + Store::Type> *get_typed_store() const { typedef typename RemoveConst::Type NCT; - Store *s=dynamic_cast *>(store); + Store *s = dynamic_cast *>(store); if(!s) - throw InvalidState("Type mismatch"); - return s->data; + throw type_mismatch(typeid(T), (store ? store->type_id() : typeid(void))); + return s; + } + +public: + template + T &value() + { + return get_typed_store()->data; + } + + template + const T &value() const + { + return get_typed_store()->data; } template