From 1bdfedf3c6dfed1b8f503696d44ea74e0db8c465 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o=20Lam?= Date: Fri, 2 Mar 2018 23:27:29 +0100 Subject: [PATCH] Common: Add a Result class This adds a lightweight, easy to use std::variant wrapper intended to be used as a return type for functions that can return either a result or an error code. --- Source/Core/Common/Common.vcxproj | 1 + Source/Core/Common/Common.vcxproj.filters | 1 + Source/Core/Common/Result.h | 30 +++++++++++++++++++++++ 3 files changed, 32 insertions(+) create mode 100644 Source/Core/Common/Result.h diff --git a/Source/Core/Common/Common.vcxproj b/Source/Core/Common/Common.vcxproj index a518b531f1..5b64898b7b 100644 --- a/Source/Core/Common/Common.vcxproj +++ b/Source/Core/Common/Common.vcxproj @@ -138,6 +138,7 @@ + diff --git a/Source/Core/Common/Common.vcxproj.filters b/Source/Core/Common/Common.vcxproj.filters index 50ea0f619d..58b75ff30f 100644 --- a/Source/Core/Common/Common.vcxproj.filters +++ b/Source/Core/Common/Common.vcxproj.filters @@ -59,6 +59,7 @@ + diff --git a/Source/Core/Common/Result.h b/Source/Core/Common/Result.h new file mode 100644 index 0000000000..2c4f47b3d7 --- /dev/null +++ b/Source/Core/Common/Result.h @@ -0,0 +1,30 @@ +// Copyright 2018 Dolphin Emulator Project +// Licensed under GPLv2+ +// Refer to the license.txt file included. + +#pragma once + +#include + +namespace Common +{ +template +class Result final +{ +public: + Result(ResultCode code) : m_variant{code} {} + Result(const T& t) : m_variant{t} {} + Result(T&& t) : m_variant{std::move(t)} {} + explicit operator bool() const { return Succeeded(); } + bool Succeeded() const { return std::holds_alternative(m_variant); } + // Must only be called when Succeeded() returns false. + ResultCode Error() const { return std::get(m_variant); } + // Must only be called when Succeeded() returns true. + const T& operator*() const { return std::get(m_variant); } + const T* operator->() const { return &std::get(m_variant); } + T& operator*() { return std::get(m_variant); } + T* operator->() { return &std::get(m_variant); } +private: + std::variant m_variant; +}; +} // namespace Common