GCC Code Coverage Report


Directory: gridformat/
File: gridformat/common/optional_reference.hpp
Date: 2024-11-10 16:24:00
Exec Total Coverage
Lines: 7 7 100.0%
Functions: 27 46 58.7%
Branches: 0 0 -%

Line Branch Exec Source
1 // SPDX-FileCopyrightText: 2022-2023 Dennis Gläser <dennis.glaeser@iws.uni-stuttgart.de>
2 // SPDX-License-Identifier: MIT
3 /*!
4 * \file
5 * \ingroup Common
6 * \brief GridFormat::OptionalReference
7 */
8 #ifndef GRIDFORMAT_COMMON_OPTIONAL_REFERENCE_HPP_
9 #define GRIDFORMAT_COMMON_OPTIONAL_REFERENCE_HPP_
10
11 #include <type_traits>
12 #include <functional>
13 #include <optional>
14
15 namespace GridFormat {
16
17 /*!
18 * \ingroup Common
19 * \brief Contains an optional reference to T.
20 * Can be used e.g. in search algorithms that, if successful,
21 * return a reference to T and none if the search failed.
22 */
23 template<typename T>
24 class OptionalReference {
25 public:
26 73738 OptionalReference() = default;
27 200086 OptionalReference(T& ref) : _ref{ref} {}
28
29 1 void release() { _ref.reset(); }
30
31 75812 T& unwrap() requires(!std::is_const_v<T>) { return _ref.value(); }
32 63173 const T& unwrap() const { return _ref.value(); }
33
34 4 bool has_value() const { return _ref.has_value(); }
35 273819 operator bool() const { return _ref.has_value(); }
36
37 private:
38 std::optional<std::reference_wrapper<T>> _ref;
39 };
40
41 template<typename T>
42 OptionalReference(T&) -> OptionalReference<T>;
43
44 } // namespace GridFormat
45
46 #endif // GRIDFORMAT_COMMON_OPTIONAL_REFERENCE_HPP_
47