X-Git-Url: http://git.tdb.fi/?a=blobdiff_plain;f=source%2Fcore%2Fvariant.h;h=f2d2ee563f339bb8b64eb020b516c3792b1db08f;hb=6a38983c19fe78753962288e206c5817ad595448;hp=6425fbfcbf7e4046d58105b445563f5e4d221acd;hpb=3553d02ef9cf66ae5ff16dd0b129815f144857a1;p=libs%2Fcore.git diff --git a/source/core/variant.h b/source/core/variant.h index 6425fbf..f2d2ee5 100644 --- a/source/core/variant.h +++ b/source/core/variant.h @@ -1,24 +1,36 @@ /* $Id$ This file is part of libmspcore -Copyright © 2006-2007 Mikko Rasa, Mikkosoft Productions +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 const std::type_info &type_id() const = 0; + virtual StoreBase *clone() const = 0; }; template @@ -27,6 +39,9 @@ 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); } }; StoreBase *store; @@ -35,13 +50,21 @@ public: Variant(): store(0) { } template Variant(const T &v): store(new Store::Type>(v)) { } + Variant(const Variant &v): store(v.store ? v.store->clone() : 0) { } ~Variant() { delete store; } template 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); return *this; } @@ -49,9 +72,9 @@ public: T &value() const { typedef typename RemoveConst::Type NCT; - Store *s=dynamic_cast *>(store); + Store *s = dynamic_cast *>(store); if(!s) - throw InvalidState("Type mismatch"); + throw type_mismatch(typeid(T), (store ? store->type_id() : typeid(void))); return s->data; }