Advertisement
slatenails

Untitled

Aug 28th, 2013
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.13 KB | None | 0 0
  1. #ifndef COBALT_TYPEDPOINTER_H
  2. #define COBALT_TYPEDPOINTER_H
  3.  
  4. #include <cassert>
  5. #include <typeinfo>
  6.  
  7. // =============================================================================
  8. // Essentially a void* pointer which remembers its type. Check type with ::type()
  9. // before using castTo because if the types mismatch you net yourself an assertion
  10. // failure!
  11. // -----------------------------------------------------------------------------
  12. class TypedPointer {
  13. public:
  14.     template<class T> TypedPointer (T* ptr) :
  15.         m_ptr (ptr),
  16.         m_type (&typeid (*ptr)) {}
  17.    
  18.     TypedPointer (std::nullptr_t) :
  19.         m_ptr (nullptr),
  20.         m_type (&typeid (std::nullptr_t)) {}
  21.    
  22.     // Get this pointer as T*.
  23.     template<class T> T* castTo() const {
  24.         if (m_ptr == nullptr)
  25.             return nullptr;
  26.        
  27.         assert (typeid (T) == *m_type);
  28.         return reinterpret_cast<T*> (m_ptr);
  29.     }
  30.    
  31.     template<class T> T& value() {
  32.         return *castTo<T>();
  33.     }
  34.    
  35.     inline void* ptr() const {
  36.         return m_ptr;
  37.     }
  38.    
  39.     inline const std::type_info& type() const {
  40.         return *m_type;
  41.     }
  42.    
  43. private:
  44.     void* m_ptr;
  45.     const std::type_info* m_type;
  46. };
  47.  
  48. #endif // COBALT_TYPEDPOINTER_H
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement