MeshKit  1.0
myany.hpp
Go to the documentation of this file.
00001 
00002 // myany.hpp
00003 #include <memory>
00004 #include <stdexcept>
00005 
00006 struct myany
00007 {
00008     myany() = default;
00009     template <typename T> myany(T const& v) : _storage(new storage<T>(v)) { }
00010     myany(myany const& other) : _storage()
00011     {
00012         if (other._storage)
00013             _storage = std::move(other._storage->clone());
00014     }
00015 
00016     void swap(myany& other)               { _storage.swap(other._storage); }
00017     friend void swap(myany& a, myany& b) { a.swap(b); }
00018     myany& operator=(myany other)        { swap(other); return *this; }
00019 
00020     // todo move semantics
00021 private:
00022     struct storage_base {
00023         virtual std::unique_ptr<storage_base> clone() = 0;
00024         virtual ~storage_base() { }
00025     };
00026     template <typename T>
00027     struct storage : storage_base {
00028         T value;
00029         explicit storage(T const& v) : value(v) {}
00030         std::unique_ptr<storage_base> clone() { return std::unique_ptr<storage_base>(new storage<T>(value)); }
00031     };
00032     std::unique_ptr<storage_base> _storage;
00033     template<typename T> friend T      & any_cast(myany      &);
00034     template<typename T> friend T const& any_cast(myany const&);
00035 };
00036 
00037 template <typename T> T& any_cast(myany& a) {
00038     if (auto p = dynamic_cast<myany::storage<T>*>(a._storage.get()))
00039         return p->value;
00040     else
00041         throw std::bad_cast();
00042 }
00043 
00044 template <typename T> T const& any_cast(myany const& a) {
00045     if (auto p = dynamic_cast<myany::storage<T> const*>(a._storage.get()))
00046         return p->value;
00047     else
00048         throw std::bad_cast();
00049 }
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines