Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sstream>
- #include <typeinfo>
- class any {
- struct type_eraser {
- virtual ~type_eraser() = default;
- virtual const std::type_info& info() = 0;
- } *_ptr;
- template<typename T>
- struct type_holder : type_eraser {
- T value;
- virtual const std::type_info& info() override {
- return typeid(T);
- }
- };
- public:
- any()
- : _ptr(nullptr)
- {}
- template<typename T>
- any(const T& val) {
- _ptr = new type_holder<T>;
- static_cast<type_holder<T>*>(_ptr)->value = val;
- }
- ~any() {
- reset();
- }
- void reset() {
- if (_ptr) {
- delete _ptr;
- _ptr = nullptr;
- }
- }
- const std::type_info& type() {
- if (_ptr)
- return _ptr->info();
- else
- return typeid(void);
- }
- template<typename T>
- T unbox() {
- if (typeid(T) == type()) {
- return static_cast<type_holder<T>*>(_ptr)->value;
- }
- else {
- std::stringstream msg_str;
- msg_str << "Failed to unbox from type '" << type().name() << "' to type '" << typeid(T).name() << '\'';
- throw std::runtime_error{msg_str.str()};
- }
- }
- };
Add Comment
Please, Sign In to add comment