vcpkg/toolsrc/include/vcpkg_optional.h

79 lines
1.8 KiB
C
Raw Normal View History

2017-01-31 08:14:48 +08:00
#pragma once
2017-03-29 06:05:55 +08:00
#include "LineInfo.h"
#include "vcpkg_Checks.h"
2017-01-31 08:14:48 +08:00
2017-03-29 06:05:55 +08:00
namespace vcpkg
{
2017-04-04 07:27:51 +08:00
struct NullOpt
2017-03-29 06:05:55 +08:00
{
2017-04-04 07:27:51 +08:00
explicit constexpr NullOpt(int) {}
2017-03-29 06:05:55 +08:00
};
2017-04-04 07:27:51 +08:00
const static constexpr NullOpt nullopt{ 0 };
2017-03-29 06:05:55 +08:00
template <class T>
2017-04-04 07:27:51 +08:00
class Optional
2017-03-29 06:05:55 +08:00
{
public:
// Constructors are intentionally implicit
2017-04-04 07:27:51 +08:00
constexpr Optional(NullOpt) : m_is_present(false), m_t() { }
2017-03-29 06:05:55 +08:00
2017-04-04 07:27:51 +08:00
Optional(const T& t) : m_is_present(true), m_t(t) { }
2017-03-29 06:05:55 +08:00
2017-04-04 07:27:51 +08:00
Optional(T&& t) : m_is_present(true), m_t(std::move(t)) { }
2017-03-29 06:05:55 +08:00
T&& value_or_exit(const LineInfo& line_info) &&
2017-03-29 06:05:55 +08:00
{
this->exit_if_null(line_info);
return std::move(this->m_t);
}
const T& value_or_exit(const LineInfo& line_info) const &
2017-03-29 06:05:55 +08:00
{
this->exit_if_null(line_info);
return this->m_t;
}
constexpr explicit operator bool() const
{
return this->m_is_present;
}
constexpr bool has_value() const
{
return m_is_present;
}
template <class U>
T value_or(U&& default_value) const &
{
return bool(*this) ? this->m_t : static_cast<T>(std::forward<U>(default_value));
}
template <class U>
T value_or(U&& default_value) &&
{
return bool(*this) ? std::move(this->m_t) : static_cast<T>(std::forward<U>(default_value));
}
const T* get() const
{
return bool(*this) ? &this->m_t : nullptr;
}
T* get()
{
return bool(*this) ? &this->m_t : nullptr;
}
private:
void exit_if_null(const LineInfo& line_info) const
{
Checks::check_exit(line_info, this->m_is_present, "Value was null");
}
bool m_is_present;
T m_t;
};
}