Audacity 3.2.0
Result.h
Go to the documentation of this file.
1/*
2 * SPDX-License-Identifier: GPL-2.0-or-later
3 * SPDX-FileName: Result.h
4 * SPDX-FileContributor: Dmitry Vedenko
5 */
6
7#pragma once
8
9#include <type_traits>
10#include <variant>
11
12#include "Error.h"
13
14namespace audacity::sqlite
15{
17template<typename T>
18class Result final
19{
20public:
21 Result() = default;
22
23 Result(T&& value) noexcept(std::is_nothrow_move_constructible_v<T>)
24 : mValue (std::forward<T>(value))
25 {
26 }
27
28 Result (const Error& error) noexcept(std::is_nothrow_copy_constructible_v<Error>)
29 : mValue (error)
30 {
31 }
32
33 Result (Error&& error) noexcept(std::is_nothrow_move_constructible_v<Error>)
34 : mValue (std::move(error))
35 {
36 }
37
38 bool HasValue () const noexcept
39 {
40 return std::holds_alternative<T>(mValue);
41 }
42
44 {
45 if (!HasValue())
46 std::get_if<Error>(&mValue)->Raise();
47
48 return *std::get_if<T>(&mValue);
49 }
50
51 const T& operator*() const&
52 {
53 return const_cast<Result*>(this)->operator*();
54 }
55
57 {
58 return &operator*();
59 }
60
61 const T* operator-> () const
62 {
63 return &operator*();
64 }
65
66 T&& operator* () &&
67 {
68 if (!HasValue())
69 std::get_if<Error>(&mValue)->Raise();
70
71 return std::move(*std::get_if<T>(&mValue));
72 }
73
74 explicit operator bool () const noexcept
75 {
76 return HasValue();
77 }
78
79 Error GetError () const noexcept
80 {
81 if (HasValue())
82 return Error();
83
84 return *std::get_if<Error>(&mValue);
85 }
86private:
87 std::variant<Error, T> mValue;
88};
89} // namespace audacity::sqlite
A class representing an error in SQLite.
Definition: Error.h:17
A class representing a result of an operation.
Definition: Result.h:19
bool HasValue() const noexcept
Definition: Result.h:38
const T & operator*() const &
Definition: Result.h:51
Error GetError() const noexcept
Definition: Result.h:79
Result(Error &&error) noexcept(std::is_nothrow_move_constructible_v< Error >)
Definition: Result.h:33
Result(T &&value) noexcept(std::is_nothrow_move_constructible_v< T >)
Definition: Result.h:23
std::variant< Error, T > mValue
Definition: Result.h:87
Result(const Error &error) noexcept(std::is_nothrow_copy_constructible_v< Error >)
Definition: Result.h:28