76 lines
1.5 KiB
C++
76 lines
1.5 KiB
C++
#pragma once
|
|
|
|
#include <type_traits>
|
|
#include <cstdlib>
|
|
|
|
namespace LXC::Util
|
|
{
|
|
// Custom version of std::unexpected //
|
|
template<typename ErrorType> struct FunctionFail
|
|
{
|
|
explicit FunctionFail(ErrorType _err)
|
|
: error(_err)
|
|
{
|
|
}
|
|
|
|
ErrorType error;
|
|
};
|
|
|
|
// Custom version of std::expected //
|
|
template<typename ResultType, typename ErrorType>
|
|
requires (!std::same_as<ResultType, bool>) // ResultType being bool causes issues with operator overloads
|
|
class ReturnVal
|
|
{
|
|
public:
|
|
// Constructor for function sucess //
|
|
ReturnVal(ResultType result)
|
|
: m_Result(result), m_FunctionFailed(false)
|
|
{}
|
|
|
|
// Constructor for function fail //
|
|
ReturnVal(FunctionFail<ErrorType> error)
|
|
: m_Error(error.error), m_FunctionFailed(true)
|
|
{}
|
|
|
|
// Destructor //
|
|
~ReturnVal() {}
|
|
|
|
// Different getters of the class //
|
|
|
|
inline bool Failed() const { return m_FunctionFailed; }
|
|
inline bool Suceeded() const { return !m_FunctionFailed; }
|
|
|
|
inline ResultType& Result()
|
|
{
|
|
if (Suceeded()) _LIKELY
|
|
return m_Result;
|
|
|
|
std::exit(EXIT_FAILURE);
|
|
}
|
|
|
|
inline ErrorType& Error()
|
|
{
|
|
if (Failed()) _LIKELY
|
|
return m_Error;
|
|
|
|
std::exit(EXIT_FAILURE);
|
|
}
|
|
|
|
// Operator overloads //
|
|
|
|
operator bool() const { return !m_FunctionFailed; }
|
|
operator ResultType() { return Result(); }
|
|
|
|
private:
|
|
// Union to hold either the result or the error //
|
|
union
|
|
{
|
|
ResultType m_Result;
|
|
ErrorType m_Error;
|
|
};
|
|
|
|
// Tracks what item is currently in the union //
|
|
bool m_FunctionFailed;
|
|
};
|
|
}
|