File: maybe.h

package info (click to toggle)
libwibble 0.1.9
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 500 kB
  • ctags: 1,183
  • sloc: cpp: 5,760; sh: 113; makefile: 71
file content (50 lines) | stat: -rw-r--r-- 1,103 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// -*- C++ -*-
#ifndef WIBBLE_MAYBE_H
#define WIBBLE_MAYBE_H

namespace wibble {

/*
  A Maybe type. Values of type Maybe< T > can be either Just T or
  Nothing.

  Maybe< int > foo;
  foo = Maybe::Nothing();
  // or
  foo = Maybe::Just( 5 );
  if ( !foo.nothing() ) {
    int real = foo;
  } else {
    // we haven't got anythig in foo
  }

  Maybe takes a default value, which is normally T(). That is what you
  get if you try to use Nothing as T.
*/

template <typename T>
struct Maybe {
    bool nothing() { return m_nothing; }
    T &value() { return m_value; }
    Maybe( bool n, const T &v ) : m_nothing( n ), m_value( v ) {}
    Maybe( const T &df = T() )
       : m_nothing( true ), m_value( df ) {}
    static Maybe Just( const T &t ) { return Maybe( false, t ); }
    static Maybe Nothing( const T &df = T() ) {
        return Maybe( true, df ); }
    operator T() { return value(); }
protected:
    bool m_nothing:1;
    T m_value;
};

template<>
struct Maybe< void > {
    Maybe() {}
    static Maybe Just() { return Maybe(); }
    static Maybe Nothing() { return Maybe(); }
};

}

#endif