Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- #include "boost/any.hpp"
- template<class C>
- 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
- {
- public:
- // Constructors
- value_ptr() : ptr(nullptr) {}
- value_ptr(const value_ptr&) = default;
- value_ptr(value_ptr&& other) : holder(std::move(other.holder)), ptr(other.ptr) {}
- template<class Cx>
- value_ptr(const Cx& other) : holder(other)
- {
- static_assert(std::is_base_of<C, Cx>::value, "Type must be derived from C!");
- ptr = boost::any_cast<Cx>(&holder);
- }
- template<class Cx>
- value_ptr(Cx && other) : holder(std::move(other))
- {
- static_assert(std::is_base_of<C, Cx>::value, "Type must be derived from C!");
- ptr = boost::any_cast<Cx>(&holder);
- }
- // Assignment operators
- value_ptr& operator=(const value_ptr&) = default;
- value_ptr& operator=(value_ptr&& other)
- {
- holder = std::move(other.holder);
- ptr = ptr;
- }
- template<class Cx>
- value_ptr& operator=(const Cx& other)
- {
- static_assert(std::is_base_of<C, Cx>::value, "Type must be derived from C!");
- holder = other;
- ptr = boost::any_cast<Cx>(&holder);
- }
- template<class Cx>
- value_ptr& operator=(Cx && other)
- {
- static_assert(std::is_base_of<C, Cx>::value, "Type must be derived from C!");
- holder = std::move(other);
- ptr = boost::any_cast<Cx>(&holder);
- }
- C& operator*() { return *ptr; }
- C* operator->() { return ptr; }
- bool empty() const { return holder.empty(); }
- const std::type_info& type() const { return holder.type(); }
- private:
- C* ptr;
- boost::any holder;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement