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