-
-
Save hackeris/9e1f5385c25596433769d55c81c1dd97 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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