wibble 1.1
maybe.h
Go to the documentation of this file.
1// -*- C++ -*-
2
3#include <wibble/mixin.h>
4
5#ifndef WIBBLE_MAYBE_H
6#define WIBBLE_MAYBE_H
7
8namespace wibble {
9
10/*
11 A Maybe type. Values of type Maybe< T > can be either Just T or
12 Nothing.
13
14 Maybe< int > foo;
15 foo = Maybe::Nothing();
16 // or
17 foo = Maybe::Just( 5 );
18 if ( !foo.nothing() ) {
19 int real = foo;
20 } else {
21 // we haven't got anythig in foo
22 }
23
24 Maybe takes a default value, which is normally T(). That is what you
25 get if you try to use Nothing as T.
26*/
27
28template <typename T>
29struct Maybe : mixin::Comparable< Maybe< T > > {
30 bool nothing() const { return m_nothing; }
31 T &value() { return m_value; }
32 const T &value() const { return m_value; }
33 Maybe( bool n, const T &v ) : m_nothing( n ), m_value( v ) {}
34 Maybe( const T &df = T() )
35 : m_nothing( true ), m_value( df ) {}
36 static Maybe Just( const T &t ) { return Maybe( false, t ); }
37 static Maybe Nothing( const T &df = T() ) {
38 return Maybe( true, df ); }
39 operator T() const { return value(); }
40
41 bool operator <=( const Maybe< T > &o ) const {
42 if (o.nothing())
43 return true;
44 if (nothing())
45 return false;
46 return value() <= o.value();
47 }
48protected:
49 bool m_nothing:1;
51};
52
53template<>
54struct Maybe< void > {
55 Maybe() {}
56 static Maybe Just() { return Maybe(); }
57 static Maybe Nothing() { return Maybe(); }
58};
59
60}
61
62#endif
Definition amorph.h:17
Maybe()
Definition maybe.h:55
static Maybe Nothing()
Definition maybe.h:57
static Maybe Just()
Definition maybe.h:56
Definition maybe.h:29
Maybe(bool n, const T &v)
Definition maybe.h:33
const T & value() const
Definition maybe.h:32
Maybe(const T &df=T())
Definition maybe.h:34
T m_value
Definition maybe.h:50
T & value()
Definition maybe.h:31
bool m_nothing
Definition maybe.h:49
static Maybe Just(const T &t)
Definition maybe.h:36
bool nothing() const
Definition maybe.h:30
bool operator<=(const Maybe< T > &o) const
Definition maybe.h:41
static Maybe Nothing(const T &df=T())
Definition maybe.h:37
Definition amorph.h:30
Definition mixin.h:13