Advertisement
iggr

typeErasure

Mar 24th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.94 KB | None | 0 0
  1. #include <utility>            //std::swap
  2.  
  3. struct ICloneable
  4. {
  5.     virtual ICloneable* clone() const = 0;
  6.     virtual ~ICloneable() { }
  7. };
  8.  
  9.  
  10. template <typename T>
  11. struct ValueHolder : public ICloneable {
  12.     T data_;
  13.  
  14.     ValueHolder(const T& value)
  15.        : data_(value){}
  16.  
  17.     ValueHolder*  clone() const
  18.     {
  19.         return new ValueHolder(data_);
  20.     }
  21.  
  22.     ~ValueHolder(){}
  23. };
  24.  
  25.  
  26. class Any {                              //this class will store objects of any type
  27.     private:
  28.          ICloneable * storage_;         //pointer to ValueHolder, stored as pointer to ICloneable
  29.  
  30.     public:
  31.          Any()
  32.            : storage_(nullptr)  {}
  33.  
  34.          template <class T>
  35.          Any(const T& val)                                  
  36.             : storage_(new ValueHolder<T>(val))   {}  
  37.  
  38.          Any(const Any& bro)
  39.             : storage_( bro.storage_ ? bro.storage_->clone() : nullptr ) {}                                      
  40.                                                                                                        
  41.          ~Any() {
  42.             clean_up();
  43.           }
  44.  
  45.           void clean_up(){
  46.               if(storage_) { delete storage_;  }
  47.           }
  48.          
  49.           Any& operator = (const Any& bro) {
  50.               Any tmp(bro);
  51.               std::swap(storage_, tmp.storage_);
  52.               return *this;
  53.               }
  54.  
  55.           template <class T>
  56.           Any& operator = (const T& val) {
  57.               Any tmp(val);
  58.               std::swap(storage_, tmp.storage_);
  59.               return *this;
  60.           }
  61.  
  62.           template <class T>
  63.           T* cast() const
  64.           {
  65.               if (storage_) {
  66.                   ValueHolder<T>* holder = dynamic_cast<ValueHolder<T>*> (storage_) ;
  67.                   if (holder) {                        
  68.                       return  & holder->data_;
  69.                   }
  70.               }
  71.               return nullptr;
  72.           }
  73.  
  74. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement