#pragma once // borrow.hpp - a non-null, unowned, pointer // // Copyright © 2014 Ben Longbons // // This file is part of The Mana World (Athena server) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . #include "fwd.hpp" #include #include #include "option.hpp" // unit tests currention in option_test.cpp namespace tmwa { // TODO see if const-by-default is a thing template class Borrowed { T *stupid; public: Borrowed() = delete; explicit Borrowed(T *p) : stupid(p) { if (!p) abort(); } T& operator *() const { return *stupid; } T *operator ->() const { return stupid; } template Borrowed downcast_to() const { static_assert(std::is_base_of::value, "base check"); static_assert(!std::is_same::value, "same check"); return Borrowed(static_cast(stupid)); } template Borrowed upcast_to() const { static_assert(std::is_base_of::value, "base check"); static_assert(!std::is_same::value, "same check"); return Borrowed(stupid); } friend bool operator == (Borrowed l, Borrowed r) { return l.stupid == r.stupid; } friend bool operator != (Borrowed l, Borrowed r) { return !(l == r); } }; namespace option { template class OptionRepr> { T *stupider; public: void set_none() { stupider = nullptr; } void post_set_some() {} bool is_some() const { return stupider != nullptr; } Borrowed *ptr() { return reinterpret_cast *>(&stupider); } const Borrowed *ptr() const { return reinterpret_cast *>(&stupider); } }; } template using P = Borrowed; template Borrowed borrow(T& ref) { return Borrowed(&ref); } template T *as_raw_pointer(Option> ptr) { return &*TRY_UNWRAP(ptr, return nullptr); } } // namespace tmwa