File: Result.h

package info (click to toggle)
audacity 3.7.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 125,252 kB
  • sloc: cpp: 358,238; ansic: 75,458; lisp: 7,761; sh: 3,410; python: 1,503; xml: 1,385; perl: 854; makefile: 122
file content (89 lines) | stat: -rw-r--r-- 1,625 bytes parent folder | download | duplicates (2)
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
84
85
86
87
88
89
/*
 * SPDX-License-Identifier: GPL-2.0-or-later
 * SPDX-FileName: Result.h
 * SPDX-FileContributor: Dmitry Vedenko
 */

#pragma once

#include <type_traits>
#include <variant>

#include "Error.h"

namespace audacity::sqlite
{
//! A class representing a result of an operation
template<typename T>
class Result final
{
public:
   Result() = default;

   Result(T&& value) noexcept(std::is_nothrow_move_constructible_v<T>)
      : mValue (std::forward<T>(value))
   {
   }

   Result (const Error& error) noexcept(std::is_nothrow_copy_constructible_v<Error>)
      : mValue (error)
   {
   }

   Result (Error&& error) noexcept(std::is_nothrow_move_constructible_v<Error>)
      : mValue (std::move(error))
   {
   }

   bool HasValue () const noexcept
   {
      return std::holds_alternative<T>(mValue);
   }

   T& operator* () &
   {
      if (!HasValue())
         std::get_if<Error>(&mValue)->Raise();

      return *std::get_if<T>(&mValue);
   }

   const T& operator*() const&
   {
      return const_cast<Result*>(this)->operator*();
   }

   T* operator-> ()
   {
      return &operator*();
   }

   const T* operator-> () const
   {
      return &operator*();
   }

   T&& operator* () &&
   {
      if (!HasValue())
         std::get_if<Error>(&mValue)->Raise();

      return std::move(*std::get_if<T>(&mValue));
   }

   explicit operator bool () const noexcept
   {
      return HasValue();
   }

   Error GetError () const noexcept
   {
      if (HasValue())
         return Error();

      return *std::get_if<Error>(&mValue);
   }
private:
   std::variant<Error, T> mValue;
};
} // namespace audacity::sqlite