Skip to content

Instantly share code, notes, and snippets.

@DieHertz
Last active August 9, 2017 11:45
Show Gist options
  • Save DieHertz/9807241 to your computer and use it in GitHub Desktop.
Save DieHertz/9807241 to your computer and use it in GitHub Desktop.
#ifndef any_h
#define any_h
namespace utility {
class any {
struct impl_base {
virtual impl_base* clone() const = 0;
virtual ~impl_base() = default;
};
template<typename T> struct impl : impl_base {
template<typename U> impl(U&& value) : value{forward<U>(value)} {}
virtual impl* clone() const override { return new impl{value}; }
T value;
};
impl_base* pimpl = nullptr;
public:
any() = default;
~any() { delete pimpl; }
template<typename T> any(T&& t) : pimpl{new impl<T>{forward<T>(t)}} {}
any(const any& other) : pimpl{other.pimpl->clone()} {}
any(any&& other) noexcept : pimpl{other.pimpl} { other.pimpl = nullptr; }
any& operator=(const any& other) { delete pimpl; pimpl = other.pimpl->clone(); return *this; }
any& operator=(any&& other) noexcept { std::swap(pimpl, other.pimpl); return *this; }
template<typename T> T& get() noexcept { return static_cast<impl<T>*>(pimpl)->value; }
// template<typename T> bool is() { return dynamic_cast<impl<T>*>(pimpl); }
};
} /* namespace any */
#endif /* any_h */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment