// optional.h - v1.2 /* * Copyright (c) 2010 Leigh Johnston. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of Leigh Johnston nor the names of any * other contributors to this software may be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef LIB_OPTIONAL #define LIB_OPTIONAL #include #include "vecarray.h" namespace lib { template class optional : private vecarray { public: typedef T value_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; private: typedef vecarray base; public: // construction optional() {} optional(const optional& rhs) : base(rhs) {} optional(const_reference value) : base(1, value) {} // state bool valid() const { return !base::empty(); } bool invalid() const { return !valid(); } operator bool() const { return valid(); } bool operator==(const optional& rhs) const { return valid() == rhs.valid() && (!valid() || get() == rhs.get()); } bool operator!=(const optional& rhs) const { return !operator==(rhs); } // element access reference get() { assert(valid()); return base::operator[](0); } const_reference get() const { assert(valid()); return base::operator[](0); } reference operator*() { return get(); } const_reference operator*() const { return get(); } pointer operator->() { return &get(); } const_pointer operator->() const { return &get(); } // modifiers void reset() { base::clear(); } optional& operator=(const optional& rhs) { optional(rhs).swap(*this); return *this; } optional& operator=(const_reference value) { optional(value).swap(*this); return *this; } void swap(optional& rhs) { base::swap(rhs); } }; } #endif // LIB_OPTIONAL