General Purpose library for Freestanding C++ and POSIX systems
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 

90 rindas
1.3 KiB

#pragma once
#include "gp_config.hpp"
#include "gp/algorithm/modifiers.hpp"
#include "gp/algorithm/move.hpp"
#include "gp/exception.hpp"
#include <type_traits>
#include <new>
namespace gp{
struct nullopt_t{};
constexpr nullopt_t nullopt;
template<typename T>
class optional{
bool ready = false;
char buffer[sizeof(T)];
public:
constexpr optional()
: ready{false}
{}
constexpr optional(nullopt_t)
: ready{false}
{}
constexpr optional(T& value)
: ready{true}
{
new(buffer) T(value);
}
constexpr optional(T&& value)
: ready{true}
{
new(buffer) T(gp::move(value));
}
optional& operator=(nullopt_t) {
if(ready) {
((T*)buffer)->~T();
ready = false;
}
return *this;
}
optional& operator=(T& value) {
if(ready) {
*(T*)buffer = value;
} else {
ready = true;
new(buffer) T(value);
}
return *this;
}
optional& operator=(T&& value) {
if(ready) {
*(T*)buffer = gp::move(value);
} else {
ready = true;
new(buffer) T(gp::move(value));
}
return *this;
}
constexpr bool has_value()
{
return ready;
}
constexpr T& value()
{
if constexpr (gp_config::has_exceptions)
{
if(!ready)
{
throw bad_optional{};
}
} else {
gp_config::assertion(ready, "bad optional access");
}
return *reinterpret_cast<T*>(buffer);
}
};
}