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:
- virtual ~InnerBase() = default;
- };
- template <class T>
- class Inner : public InnerBase {
- public:
- Inner(const T& value) : value_(value) {
- }
- T value_;
- };
- Any() {
- }
- template <class T>
- Any& operator=(const T& value) {
- ptr_.reset(new Inner<T>(value));
- return *this;
- }
- Any(const Any& rhs) : ptr_(new Inner<decltype(*(rhs.ptr_.get()))>(*(rhs.ptr_.get()))) {
- }
- Any& operator=(const Any& rhs) {
- if (ptr_ != rhs.ptr_) {
- Any copy(rhs);
- Swap(copy);
- }
- return *this;
- }
- template <class T>
- Any(T&& value) : ptr_(new Inner<T>(std::forward<T>(value))) {
- }
- ~Any() {
- ptr_.release();
- }
- bool Empty() const {
- return (ptr_ == nullptr);
- }
- void Clear() {
- ptr_.release();
- }
- void Swap(Any& rhs) {
- std::swap(ptr_, rhs.ptr_);
- }
- template <class T>
- const T& GetValue() const {
- std::cerr << __PRETTY_FUNCTION__ << std::endl;
- if (std::is_same_v<T, decltype(*(ptr_.get()))>) {
- std::cerr << "yay\n";
- }
- try {
- dynamic_cast<Inner<T>&>(*ptr_).value_;
- } catch (...) {
- throw std::bad_cast();
- }
- return dynamic_cast<Inner<T>&>(*ptr_).value_;
- }
- private:
- std::unique_ptr<InnerBase> ptr_ = nullptr;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement