// optional.h - v1.0.1 /* * Copyright (c) 2008 Leigh Johnston. All Rights Reserved. * * Permission to use, copy, modify and distribute this * software and its documentation for any purpose is hereby * granted, provided that the above copyright notice * appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation. * The author makes no representations about the * suitability of this software for any purpose. It is provided * "as is" without express or implied warranty. */ #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(); } // 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