X-Git-Url: http://git.tdb.fi/?a=blobdiff_plain;f=source%2Fcore%2Fvariant.h;h=e00885c94210ef720c3d48c42769d99a7d3182f8;hb=79482ba7aea1b79c7a310c940cc0292532ef3bcb;hp=b81bb506f300f8df2f215a63a427a7df38af7f7e;hpb=773a089db67a6293ac057e3160a43cceab8e5c1e;p=libs%2Fcore.git diff --git a/source/core/variant.h b/source/core/variant.h index b81bb50..e00885c 100644 --- a/source/core/variant.h +++ b/source/core/variant.h @@ -1,23 +1,29 @@ -/* $Id$ - -This file is part of libmspcore -Copyright © 2006-2007 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 @@ -26,6 +32,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; @@ -33,30 +42,39 @@ private: public: Variant(): store(0) { } template - Variant(T v): store(new Store(v)) { } + 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=(T v) + Variant &operator=(const T &v) + { + delete store; + store = new Store::Type>(v); + return *this; + } + + Variant &operator=(const Variant &v) { delete store; - store=new Store(v); + store = (v.store ? v.store->clone() : 0); return *this; } template - T value() const + T &value() const { - Store *s=dynamic_cast *>(store); + typedef typename RemoveConst::Type NCT; + 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; } template bool check_type() const { - return dynamic_cast *>(store)!=0; + return dynamic_cast::Type> *>(store)!=0; } template