wibble
1.1
Main Page
Namespaces
Classes
Files
File List
File Members
wibble
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
8
namespace
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
28
template
<
typename
T>
29
struct
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
}
48
protected
:
49
bool
m_nothing
:1;
50
T
m_value
;
51
};
52
53
template
<>
54
struct
Maybe
< void > {
55
Maybe
() {}
56
static
Maybe
Just
() {
return
Maybe
(); }
57
static
Maybe
Nothing
() {
return
Maybe
(); }
58
};
59
60
}
61
62
#endif
Generated on Wed Oct 23 2013 17:14:25 for wibble by
1.8.4