F´ Flight Software - C/C++ Documentation
A framework for building embedded system applications to NASA flight quality standards.
Loading...
Searching...
No Matches
Option.hpp
Go to the documentation of this file.
1// ======================================================================
2// \title Option.hpp
3// \author Rob Bocchino
4// \brief An option type for unit testing
5//
6// \copyright
7// Copyright (C) 2023 California Institute of Technology.
8// ALL RIGHTS RESERVED. United States Government Sponsorship
9// acknowledged. Any commercial use must be negotiated with the Office
10// of Technology Transfer at the California Institute of Technology.
11// ======================================================================
12
13#ifndef TestUtils_Option_HPP
14#define TestUtils_Option_HPP
15
16namespace TestUtils {
17
19template <typename T, T noValue = T()>
20class Option {
21 private:
22 enum class State { VALUE, NO_VALUE };
23
24 public:
25 explicit Option(T value) : state(State::VALUE), value(value) {}
26 Option() : state(State::NO_VALUE), value(noValue) {}
27
28 public:
29 static Option<T> some(T value) { return Option(value); }
30 static constexpr Option<T> none() { return Option(); }
31
32 public:
33 bool hasValue() const { return this->state == State::VALUE; }
34 void set(T value) {
35 this->state = State::VALUE;
36 this->value = value;
37 }
38 void clear() { this->state = State::NO_VALUE; }
39 T get() const {
40 FW_ASSERT(this->hasValue());
41 return this->value;
42 }
43 T getOrElse(T value) const {
44 T result = value;
45 if (this->hasValue()) {
46 result = this->value;
47 }
48 return result;
49 }
50
51 private:
52 State state;
53 T value;
54};
55
56} // namespace TestUtils
57
58#endif
#define FW_ASSERT(...)
Definition Assert.hpp:14
An optional value.
Definition Option.hpp:20
T getOrElse(T value) const
Definition Option.hpp:43
static Option< T > some(T value)
Definition Option.hpp:29
Option(T value)
Definition Option.hpp:25
static constexpr Option< T > none()
Definition Option.hpp:30
T get() const
Definition Option.hpp:39
bool hasValue() const
Definition Option.hpp:33
void set(T value)
Definition Option.hpp:34