Guest User

Untitled

a guest
Feb 25th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. #include <sstream>
  2. #include <typeinfo>
  3.  
  4. class any {
  5. struct type_eraser {
  6. virtual ~type_eraser() = default;
  7. virtual const std::type_info& info() = 0;
  8. } *_ptr;
  9.  
  10. template<typename T>
  11. struct type_holder : type_eraser {
  12. T value;
  13. virtual const std::type_info& info() override {
  14. return typeid(T);
  15. }
  16. };
  17.  
  18. public:
  19. any()
  20. : _ptr(nullptr)
  21. {}
  22.  
  23. template<typename T>
  24. any(const T& val) {
  25. _ptr = new type_holder<T>;
  26. static_cast<type_holder<T>*>(_ptr)->value = val;
  27. }
  28.  
  29. ~any() {
  30. reset();
  31. }
  32.  
  33. void reset() {
  34. if (_ptr) {
  35. delete _ptr;
  36. _ptr = nullptr;
  37. }
  38. }
  39.  
  40. const std::type_info& type() {
  41. if (_ptr)
  42. return _ptr->info();
  43. else
  44. return typeid(void);
  45. }
  46.  
  47. template<typename T>
  48. T unbox() {
  49. if (typeid(T) == type()) {
  50. return static_cast<type_holder<T>*>(_ptr)->value;
  51. }
  52. else {
  53. std::stringstream msg_str;
  54. msg_str << "Failed to unbox from type '" << type().name() << "' to type '" << typeid(T).name() << '\'';
  55. throw std::runtime_error{msg_str.str()};
  56. }
  57. }
  58. };
Add Comment
Please, Sign In to add comment