#pragma once #include #include #include #include #include namespace Void::Variant { // ── overload ────────────────────────────────────────────────────────────────── // Aggregate multiple callables into one visitor. Usage: // std::visit(overload{[](int i){...}, [](std::string s){...}}, v); template struct overload : Fs... { using Fs::operator()...; }; // ── match ───────────────────────────────────────────────────────────────────── // Apply visitor lambdas to a std::variant inline. Usage: // match(v, [](int i){ return i; }, [](double d){ return (int)d; }); template [[nodiscard]] decltype(auto) match(V&& v, Fs&&... fs) { return std::visit(overload...>{std::forward(fs)...}, std::forward(v)); } // ── holds ────────────────────────────────────────────────────────────────── // Compile-time-named alternative to std::holds_alternative. template [[nodiscard]] bool holds(const V& v) noexcept { return std::holds_alternative(v); } // ── get_or ───────────────────────────────────────────────────────────────── // Returns the value if the variant holds T, otherwise returns default_val. template [[nodiscard]] T get_or(const V& v, T default_val) noexcept { if (const auto* p = std::get_if(&v)) return *p; return default_val; } // ── try_get ──────────────────────────────────────────────────────────────── // Returns optional — present iff the variant holds T. template [[nodiscard]] std::optional try_get(const V& v) noexcept { if (const auto* p = std::get_if(&v)) return *p; return std::nullopt; } // ── index_of ──────────────────────────────────────────────────────────── // Compile-time index of T within a std::variant<...> type V. namespace Detail { template constexpr std::size_t variant_index() { if constexpr (I >= std::variant_size_v) return std::variant_npos; else if constexpr (std::is_same_v>) return I; else return variant_index(); } } // namespace Detail template inline constexpr std::size_t index_of = Detail::variant_index(); // ── apply_to ─────────────────────────────────────────────────────────────── // Call fn only if the variant holds T. Returns optional of the result. template [[nodiscard]] auto apply_to(const V& v, F&& fn) -> std::optional> { if (const auto* p = std::get_if(&v)) return std::invoke(std::forward(fn), *p); return std::nullopt; } // ── narrow ───────────────────────────────────────────────────────────── // Map variant: if the active type is convertible to U, return U; else nullopt. template [[nodiscard]] std::optional narrow(const std::variant& v) { return std::visit([](const auto& alt) -> std::optional { using T = std::decay_t; if constexpr (std::is_convertible_v) return static_cast(alt); else return std::nullopt; }, v); } } // namespace Void::Variant