vcpkg/toolsrc/include/vcpkg_expected.h

70 lines
1.6 KiB
C
Raw Normal View History

2016-09-19 11:50:08 +08:00
#pragma once
#include "vcpkg_Checks.h"
#include <system_error>
2016-09-19 11:50:08 +08:00
namespace vcpkg
{
template<class T>
2017-04-04 07:26:54 +08:00
class Expected
2016-09-19 11:50:08 +08:00
{
public:
2017-04-01 07:33:10 +08:00
// Constructors are intentionally implicit
Expected(const std::error_code& ec) : m_error_code(ec), m_t() {}
2016-09-19 11:50:08 +08:00
Expected(std::errc ec) : Expected(std::make_error_code(ec)) {}
2016-09-19 11:50:08 +08:00
Expected(const T& t) : m_error_code(), m_t(t) {}
2016-09-19 11:50:08 +08:00
Expected(T&& t) : m_error_code(), m_t(std::move(t)) {}
2016-09-19 11:50:08 +08:00
Expected() : Expected(std::error_code(), T()) {}
2016-09-19 11:50:08 +08:00
2017-04-04 07:26:54 +08:00
Expected(const Expected&) = default;
Expected(Expected&&) = default;
Expected& operator=(const Expected&) = default;
Expected& operator=(Expected&&) = default;
2016-09-19 11:50:08 +08:00
std::error_code error_code() const { return this->m_error_code; }
2016-09-19 11:50:08 +08:00
T&& value_or_exit(const LineInfo& line_info) &&
2016-09-19 11:50:08 +08:00
{
exit_if_error(line_info);
2016-09-19 11:50:08 +08:00
return std::move(this->m_t);
}
const T& value_or_exit(const LineInfo& line_info) const &
2016-09-19 11:50:08 +08:00
{
exit_if_error(line_info);
2016-09-19 11:50:08 +08:00
return this->m_t;
}
const T* get() const
{
if (m_error_code)
{
return nullptr;
}
return &this->m_t;
}
T* get()
{
if (m_error_code)
{
return nullptr;
}
return &this->m_t;
}
private:
void exit_if_error(const LineInfo& line_info) const
2016-09-19 11:50:08 +08:00
{
Checks::check_exit(line_info, !this->m_error_code, this->m_error_code.message());
2016-09-19 11:50:08 +08:00
}
std::error_code m_error_code;
T m_t;
};
}