#ifndef QT_MAYBE_H #define QT_MAYBE_H #include "Either.h" /** A simple option type implementation which represents the result * of an operation which returned either a valid result or nothing. * * Maybe is built on top of Either, using one type to * hold the result (of type T) and the other to represent no result. * * Since Maybe is built on Either, it uses QVariant for the underlying * value storage and has the same size. * * Maybe instances can be constructed using the just(T) and * nothing() helper functions. */ template class Maybe { public: /** Construct a Maybe instance representing no * value. */ Maybe() : m_value(false) {} /** Returns true if this Maybe has a value. */ operator bool() const { return m_value.template is(); } /** Returns the value from this Maybe. Asserts * in debug builds if there is no value. */ T value() const { return m_value.template as(); } // helper method for the non-member just() function, // which external helpers should use instead template static Maybe just(const U& value); private: // use the just() function to create a new // Maybe instance with a value Maybe(const T& value) : m_value(value) {} Either m_value; }; template template Maybe Maybe::just(const U& value) { return Maybe(value); } // helper type used by nothing() struct NothingType { template operator Maybe() const { return Maybe(); } }; // helper type used by just() template struct JustType { JustType(const T& _value) : value(_value) {} template operator Maybe() const { return Maybe::just(value); } const T& value; }; // helper type specialized for pointer types template struct JustType { JustType(T* _value) : value(_value) {} operator Maybe() const { // just(T*) returns a no-value Maybe if the pointer // is null return value ? Maybe::just(value) : Maybe(); } T* value; }; /** Returns a type which can be implicitly cast to any Maybe type, * representing a function which returned no value. */ inline NothingType nothing() { return NothingType(); } /** Returns a type which can be implicitly cast to a Maybe type * representing a function which did return a value of @p value. * * just() is specialized for pointer types to return nothing() * if the pointer is null. */ template inline JustType just(const T& value) { return JustType(value); } #endif