Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <utility> //std::swap
- struct ICloneable
- {
- virtual ICloneable* clone() const = 0;
- virtual ~ICloneable() { }
- };
- template <typename T>
- struct ValueHolder : public ICloneable {
- T data_;
- ValueHolder(const T& value)
- : data_(value){}
- ValueHolder* clone() const
- {
- return new ValueHolder(data_);
- }
- ~ValueHolder(){}
- };
- class Any { //this class will store objects of any type
- private:
- ICloneable * storage_; //pointer to ValueHolder, stored as pointer to ICloneable
- public:
- Any()
- : storage_(nullptr) {}
- template <class T>
- Any(const T& val)
- : storage_(new ValueHolder<T>(val)) {}
- Any(const Any& bro)
- : storage_( bro.storage_ ? bro.storage_->clone() : nullptr ) {}
- ~Any() {
- clean_up();
- }
- void clean_up(){
- if(storage_) { delete storage_; }
- }
- Any& operator = (const Any& bro) {
- Any tmp(bro);
- std::swap(storage_, tmp.storage_);
- return *this;
- }
- template <class T>
- Any& operator = (const T& val) {
- Any tmp(val);
- std::swap(storage_, tmp.storage_);
- return *this;
- }
- template <class T>
- T* cast() const
- {
- if (storage_) {
- ValueHolder<T>* holder = dynamic_cast<ValueHolder<T>*> (storage_) ;
- if (holder) {
- return & holder->data_;
- }
- }
- return nullptr;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement