#include <array>
#include <cassert>
#include <iostream>
#include <string>
#include <tuple>
/**
* Similar to `optional`, but take the bool as argument.
*/
template <typename T>
class out_optional
{
public:
out_optional() {}
out_optional(const out_optional&) = delete;
out_optional& operator =(const out_optional&) = delete;
void destruct(bool b) { if (b) { reset(b); } }
void reset(bool& b) { if (b) { reinterpret_cast<T*>(data)->~T(); b = false; } }
void reset(bool& b, const T& value) { reset(b); new (data) T{value}; b = true; }
void reset(bool& b, T&& value) { reset(b); new (data) T{value}; b = true; }
const T* get_ptr(bool b) const { return b ? reinterpret_cast<T*>(data) : nullptr; }
T* get_ptr(bool b) { return b ? reinterpret_cast<T*>(data) : nullptr; }
const T& get(bool b) const { assert(b); return *get_ptr(b); }
T& get(bool b) { assert(b); return *get_ptr(b); }
// Other stuff as swap, pseudo assignment/move, more constructors
private:
alignas(T) char data[sizeof(T)];
};
/**
* 'Tuple' of optional, packaged with bool at the end.
*/
template <typename ... Ts>
struct multi_optional
{
template <std::size_t I>
using type = typename std::tuple_element<I, std::tuple<Ts...>>::type;
static_assert(std::is_same<int, type<0>>::value, "");
public:
multi_optional() = default;
~multi_optional()
{
destruct(std::index_sequence_for<Ts...>());
}
multi_optional(const multi_optional&) = delete; // To be implemented.
multi_optional& operator =(const multi_optional&) = delete; // To be implemented.
template <std::size_t I>
const auto* get_ptr() const { return std::get<I>(data).get_ptr(flags[I]); }
template <std::size_t I>
auto* get_ptr() { return std::get<I>(data).get_ptr(flags[I]); }
template <std::size_t I>
const auto& get() const { return std::get<I>(data).get(flags[I]); }
template <std::size_t I>
auto& get() { return std::get<I>(data).get(flags[I]); }
template <std::size_t I>
void reset() { return std::get<I>(data).reset(flags[I]); }
template <std::size_t I>
void reset(const type<I>& value) { return std::get<I>(data).reset(flags[I], value); }
private:
template <std::size_t ... Is>
void destruct(std::index_sequence<Is...>)
{
int dummy[] = { 0, (std::get<Is>(data).destruct(flags[Is]), 0)... };
static_cast<void>(dummy);
}
private:
std::tuple<out_optional<Ts>...> data;
std::array<bool, sizeof...(Ts)> flags = {{}};
};
int main() {
multi_optional<int, std::string> m;
assert(m.get_ptr<0>() == nullptr);
assert(m.get_ptr<1>() == nullptr);
m.reset<0>(42);
m.reset<1>("hello");
std::cout << m.get<1>() << m.get<0>() << std::endl;
m.reset<0>();
m.reset<1>();
assert(m.get_ptr<0>() == nullptr);
assert(m.get_ptr<1>() == nullptr);
}