wibble 0.1.28
maybe.h
Go to the documentation of this file.
00001 // -*- C++ -*-
00002 #ifndef WIBBLE_MAYBE_H
00003 #define WIBBLE_MAYBE_H
00004 
00005 namespace wibble {
00006 
00007 /*
00008   A Maybe type. Values of type Maybe< T > can be either Just T or
00009   Nothing.
00010 
00011   Maybe< int > foo;
00012   foo = Maybe::Nothing();
00013   // or
00014   foo = Maybe::Just( 5 );
00015   if ( !foo.nothing() ) {
00016     int real = foo;
00017   } else {
00018     // we haven't got anythig in foo
00019   }
00020 
00021   Maybe takes a default value, which is normally T(). That is what you
00022   get if you try to use Nothing as T.
00023 */
00024 
00025 template <typename T>
00026 struct Maybe : mixin::Comparable< Maybe< T > > {
00027     bool nothing() const { return m_nothing; }
00028     T &value() { return m_value; }
00029     const T &value() const { return m_value; }
00030     Maybe( bool n, const T &v ) : m_nothing( n ), m_value( v ) {}
00031     Maybe( const T &df = T() )
00032        : m_nothing( true ), m_value( df ) {}
00033     static Maybe Just( const T &t ) { return Maybe( false, t ); }
00034     static Maybe Nothing( const T &df = T() ) {
00035         return Maybe( true, df ); }
00036     operator T() const { return value(); }
00037 
00038     bool operator <=( const Maybe< T > &o ) const {
00039         if (o.nothing())
00040             return true;
00041         if (nothing())
00042             return false;
00043         return value() <= o.value();
00044     }
00045 protected:
00046     bool m_nothing:1;
00047     T m_value;
00048 };
00049 
00050 template<>
00051 struct Maybe< void > {
00052     Maybe() {}
00053     static Maybe Just() { return Maybe(); }
00054     static Maybe Nothing() { return Maybe(); }
00055 };
00056 
00057 }
00058 
00059 #endif