#ifndef RFL_BOX_HPP_ #define RFL_BOX_HPP_ #include #include namespace rfl { /// The Box class behaves very similarly to the unique_ptr, but unlike the /// unique_ptr, it is 100% guaranteed to be filled at all times. template class Box { public: /// The only way of creating new boxes is /// Box::make(...). template static Box make(Args&&... _args) { return Box(std::make_unique(std::forward(_args)...)); } Box() : ptr_(std::make_unique()) {} Box(const Box& _other) = delete; Box(Box&& _other) = default; template , bool>::type = true> Box(Box&& _other) noexcept : ptr_(std::make_unique(std::forward(*_other))) {} ~Box() = default; /// Returns a pointer to the underlying object T* get() const { return ptr_.get(); } /// Copy assignment operator Box& operator=(const Box& _other) = delete; /// Move assignment operator Box& operator=(Box&& _other) noexcept = default; /// Move assignment operator template , bool>::type = true> Box& operator=(Box&& _other) noexcept { ptr_ = std::make_unique(std::forward(*_other)); return *this; } /// Returns the underlying object. T& operator*() { return *ptr_; } /// Returns the underlying object. T& operator*() const { return *ptr_; } /// Returns the underlying object. T* operator->() { return ptr_.get(); } /// Returns the underlying object. T* operator->() const { return ptr_.get(); } /// Returns the underlying unique_ptr const std::unique_ptr& ptr() const { return ptr_; } private: /// Only make is allowed to use this constructor. explicit Box(std::unique_ptr&& _ptr) : ptr_(std::move(_ptr)) {} private: /// The underlying unique_ptr_ std::unique_ptr ptr_; }; /// Generates a new Ref. template Box make_box(Args&&... _args) { return Box::make(std::forward(_args)...); } template inline auto operator<=>(const Box& _t1, const Box& _t2) { return _t1.ptr() <=> _t2.ptr(); } template inline std::basic_ostream& operator<<( std::basic_ostream& _os, const Box& _b) { _os << _b.get(); return _os; } } // namespace rfl #endif