-
Notifications
You must be signed in to change notification settings - Fork 1
/
option.h
executable file
·69 lines (59 loc) · 1.32 KB
/
option.h
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*****************************************************************************/
/*! \file option.hh
* \author AV
* \date 2010-03
*
* \brief A simple template to mimic ML's option/None/Some
*****************************************************************************/
#ifndef OPTION_HH
#define OPTION_HH
class OptionNoValueExc {};
template <typename T>
class Option
{
T stored;
bool isSome;
public:
/*! \brief Default constructor, similar to None in ML */
Option()
{
isSome = false;
}
/*! \brief Constructor with a value, similar to Some in ML */
Option(T val)
{
stored = val;
isSome = true;
}
/*! \brief Copy constructor */
Option(const Option &other) :
stored(other.stored),
isSome(other.isSome)
{};
/*! \brief Check if a value is stored */
bool hasValue() const
{
return isSome;
}
/*! \brief Get the value if present, throw a dirty exception otherwise */
T getValue() const
{
if (!isSome)
throw OptionNoValueExc();
return stored;
}
/*! \brief Get the address of the value if present, throw a dirty exception
* otherwise */
T * getValueAddr(bool force = false)
{
if(force) isSome = true;
if (!isSome)
throw OptionNoValueExc();
return & stored;
}
void clear()
{
isSome = false;
}
};
#endif /* OPTION_HH */