Skip to content

Instantly share code, notes, and snippets.

@commander-trashdin
Created November 21, 2019 22:06
Show Gist options
  • Save commander-trashdin/876aa0eb5086a78a1f894c7d8eeb94f8 to your computer and use it in GitHub Desktop.
Save commander-trashdin/876aa0eb5086a78a1f894c7d8eeb94f8 to your computer and use it in GitHub Desktop.
#pragma once
#include <memory>
class Any {
public:
Any() = default;
template <class T>
Any(T value) : ptr_(std::make_unique<Derived<T>>(std::move(value))) {
}
template <class T>
Any(const T& value) : ptr_(std::make_unique<Derived<T>>(value)) {
}
template <class T>
Any& operator=(const T& value) {
ptr_ = std::make_unique<Base>(Derived<T>(value));
return *this;
}
Any(const Any& rhs) {
ptr_ = rhs.ptr_->Clone();
}
Any& operator=(const Any& rhs) {
ptr_ = rhs.ptr_->Clone();
return *this;
}
~Any() {
}
bool Empty() const {
if (ptr_) {
return false;
}
return true;
}
void Clear() {
ptr_ = nullptr;
}
void Swap(Any& rhs) {
std::swap(ptr_, rhs.ptr_);
}
template <class T>
const T& GetValue() const {
return (dynamic_cast<const Derived<T>&>(*ptr_)).value_;
}
private:
struct Base {
virtual ~Base() = default;
virtual std::unique_ptr<Base> Clone() = 0;
};
template <class T>
struct Derived : public Base {
Derived(T value) : value_(std::move(value)) {
}
std::unique_ptr<Base> Clone() override {
return std::make_unique<Derived<T>>(value_);
}
T value_;
};
std::unique_ptr<Base> ptr_;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment