blob: 0395945de02cd0bba6c3282bb0ad982d01261ce7 (
plain)
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
#ifndef ERROR_OR_H
#define ERROR_OR_H
#include <string>
#include "utils/macro.h"
namespace utils {
/**
* @brief The Optional class is able to keep value, manage it it is empty and
* specify error code.
* Can be used as return value of function that is not guarantee that vaue will
* be returned
*
*/
template <typename ObjectType, typename ErrorType = std::string>
class Optional {
public:
/**
* @brief The OptionalEmpty enum enum with one value to specify that Optional
* is not initialized
*/
enum OptionalEmpty { EMPTY };
/**
* @brief Optional constructor with object initialization
* @param object object to initialize Optional
*/
Optional(ObjectType& object)
: object_(&object), error_(), is_initialized_(true) {}
/**
* @brief Optional constructor with object and error initialization
* @param object object to initialize Optional
* @param error error code initialization
*/
Optional(ObjectType& object, ErrorType error)
: object_(&object), error_(error), is_initialized_(true) {}
/**
* @brief Optional constructir without object initialization
* @param empty manadatory parameter for explicit specifying that Optional is
* empty
* @param error error code initialization
*/
Optional(OptionalEmpty empty, ErrorType error)
: object_(nullptr), error_(error), is_initialized_(false) {}
/**
* @brief Optional empty optional initialization without specifying error code
* @param empty manadatory parameter for explicit specifying that Optional is
* empty
*/
Optional(OptionalEmpty empty)
: object_(nullptr), error_(), is_initialized_(false) {}
/**
* @brief operator bool operator for checking if optional is initialized
*/
operator bool() const {
return is_initialized_;
}
/**
* @brief operator * access to object
* @return
*/
ObjectType& operator*() const {
DCHECK(is_initialized_);
return *object_;
}
ErrorType error() const {
return error_;
}
private:
ObjectType* object_;
ErrorType error_;
bool is_initialized_;
};
} // utils utils
#endif // ERROR_OR_H
|