Advertisement
Guest User

Untitled

a guest
Jun 27th, 2015
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 KB | None | 0 0
  1. #pragma once
  2.  
  3. #include "boost/any.hpp"
  4.  
  5. template<class C>
  6. class value_ptr // Holds a ptr that will be treated like a value. Basically an any with a limit on that it must be derived from C
  7. {
  8. public:
  9.     // Constructors
  10.     value_ptr() : ptr(nullptr) {}
  11.     value_ptr(const value_ptr&) = default;
  12.     value_ptr(value_ptr&& other) : holder(std::move(other.holder)), ptr(other.ptr) {}
  13.  
  14.     template<class Cx>
  15.     value_ptr(const Cx& other) : holder(other)
  16.     {
  17.         static_assert(std::is_base_of<C, Cx>::value, "Type must be derived from C!");
  18.         ptr = boost::any_cast<Cx>(&holder);
  19.     }
  20.  
  21.     template<class Cx>
  22.     value_ptr(Cx && other) : holder(std::move(other))
  23.     {
  24.         static_assert(std::is_base_of<C, Cx>::value, "Type must be derived from C!");
  25.         ptr = boost::any_cast<Cx>(&holder);
  26.     }
  27.  
  28.     // Assignment operators
  29.     value_ptr& operator=(const value_ptr&) = default;
  30.     value_ptr& operator=(value_ptr&& other)
  31.     {
  32.         holder = std::move(other.holder);
  33.         ptr = ptr;
  34.     }
  35.  
  36.     template<class Cx>
  37.     value_ptr& operator=(const Cx& other)
  38.     {
  39.         static_assert(std::is_base_of<C, Cx>::value, "Type must be derived from C!");
  40.         holder = other;
  41.         ptr = boost::any_cast<Cx>(&holder);
  42.     }
  43.  
  44.     template<class Cx>
  45.     value_ptr& operator=(Cx && other)
  46.     {
  47.         static_assert(std::is_base_of<C, Cx>::value, "Type must be derived from C!");
  48.         holder = std::move(other);
  49.         ptr = boost::any_cast<Cx>(&holder);
  50.     }
  51.  
  52.     C& operator*() { return *ptr; }
  53.     C* operator->() { return ptr; }
  54.  
  55.     bool empty() const { return holder.empty(); }
  56.     const std::type_info& type() const { return holder.type(); }
  57. private:
  58.     C* ptr;
  59.     boost::any holder;
  60. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement