Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- #include <memory>
- #include <type_traits>
- #include <iostream>
- class Any {
- public:
- class InnerBase {
- public:
- using Pointer = std::unique_ptr<InnerBase>;
- virtual InnerBase* Clone() const = 0;
- virtual ~InnerBase() = default;
- };
- template <class T>
- class Inner : public InnerBase {
- public:
- Inner(const T& value) : value_(value) {
- }
- virtual InnerBase* Clone() const override {
- return new Inner(value_);
- }
- T value_;
- };
- Any() : ptr_(nullptr) {
- }
- template <class T>
- Any& operator=(const T& value) {
- ptr_.reset(new Inner<T>(value));
- return *this;
- }
- Any(const Any& rhs) {
- if (rhs.ptr_ == nullptr) {
- ptr_ = nullptr;
- } else {
- ptr_.reset(rhs.ptr_->Clone());
- }
- }
- Any& operator=(const Any& rhs) {
- if (ptr_ != rhs.ptr_) {
- Any copy(rhs);
- this->Swap(copy);
- }
- return *this;
- }
- template <class T>
- Any(const T& value) : ptr_(new Inner<T>(value)) {
- }
- ~Any() {
- ptr_.release();
- }
- bool Empty() const {
- return (ptr_ == nullptr);
- }
- void Clear() {
- if (ptr_ != nullptr) {
- ptr_.release();
- }
- }
- void Swap(Any& rhs) {
- std::swap(ptr_, rhs.ptr_);
- }
- template <class T>
- const T& GetValue() const {
- return dynamic_cast<Inner<T>&>(*ptr_).value_;
- }
- private:
- InnerBase::Pointer ptr_;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement