add tool_return pair for returning error or value.

This commit is contained in:
Kelvin Sherlock 2014-12-20 12:20:18 -05:00
parent a4e89626d5
commit 240a3ac480
2 changed files with 151 additions and 0 deletions

View File

@ -577,6 +577,20 @@ namespace MacOS {
{
return std::error_condition(static_cast<int>(e), macos_system_category());
}
inline void throw_macos_error(int e)
{
throw std::system_error(e, macos_system_category());
}
inline void throw_macos_error(int e, const char *what)
{
throw std::system_error(e, macos_system_category(), what);
}
inline void throw_macos_error(int e, const std::string &what)
{
throw std::system_error(e, macos_system_category(), what);
}
}
namespace std {

137
macos/tool_return.h Normal file
View File

@ -0,0 +1,137 @@
#ifndef __tool_return__
#define __tool_return__
#include "errors.h"
#include <utility>
namespace MacOS {
namespace internal {
class tool_return_base
{
protected:
macos_error _error;
tool_return_base() : _error(static_cast<macos_error>(0))
{}
tool_return_base(macos_error error) : _error(error)
{}
public:
macos_error error() const
{
return _error;
}
template<class... Args>
void throw_macos_error(Args&&... args) const
{
if (_error) MacOS::throw_macos_error(_error, std::forward<Args>(args)...);
}
};
} // namespace
template<class T>
class tool_return : public internal::tool_return_base
{
private:
T _value;
tool_return() = delete;
operator T() const
{
return _value;
}
public:
tool_return(T value) : _value(value)
{}
tool_return(macos_error error) : tool_return_base(error)
{}
tool_return &operator=(T value)
{
_value = value;
_error = 0;
return *this;
}
tool_return &operator=(macos_error error)
{
_value = T();
_error = error;
return *this;
}
constexpr const T* operator->() const
{
return &_value;
}
constexpr const T& operator *() const
{
return _value;
}
T value() const
{
return _value;
}
template<class U>
T value_or(U&& u) const
{
if (_error) return u;
return _value;
}
template<class... Args>
T value_or_throw(Args&&... args) const
{
if (_error) throw_macos_error(std::forward<Args>(args)...);
return _value;
}
};
template<>
class tool_return<void> : public internal::tool_return_base
{
public:
tool_return()
{}
tool_return(macos_error error) : tool_return_base(error)
{}
tool_return &operator=(macos_error error)
{
_error = error;
return *this;
}
};
} // namespace IIgs
#endif