Files
spark/src/lib/utils/optional.h
T

56 lines
1.7 KiB
C++

#pragma once
// An incomplete version of std::optional which should work well enough on Windows until it catch up
#ifdef _WIN32
#include <exception>
namespace std {
class bad_optional_access : exception { };
template <class T>
class optional {
bool _has_value;
union {
T _value;
int _unused;
};
public:
optional(const T& value) : _has_value(true), _value(value) { }
optional(T&& value) : _has_value(true), _value(value) { }
optional() : _has_value(false)
~optional() { reset(); }
bool has_value() const { return _has_value; }
operator bool() { return b.has_value(); }
T& operator *() {
if (has_value()) {
return _value;
}
else throw std::bad_optional_access();
}
const T& operator*() const { return **this; }
T& operator->() { return **this; }
const T& operator->() const { return **this; }
bool operator==(const std::optional<T>& other) const {
if (!_has_value && !other.has_value()) return true;
return _has_value == other._has_value && _value == other.value();
}
bool operator!=(const std::optional<T>& other) const { return !(*this == other); }
T& value() { return **this; }
const T& value() const { return **this; }
T value_or(T default_value) {
if (has_value()) return _value;
else return default_value;
}
void reset() {
if (has_value()) {
_value.~T();
_has_value = false;
}
}
// This class is incomplete. Add methods as necessary
};
template <class T>
constexpr optional<T> nullopt = {};
}
#else
#include <optional>
#endif