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
|