#pragma once #include #include namespace Void::Scope { // ── ScopeExit — runs on scope exit unconditionally ─────────────────────────── template class [[nodiscard]] ScopeExit { public: explicit ScopeExit(F f) noexcept(std::is_nothrow_move_constructible_v) : f_{std::move(f)} { } ScopeExit(ScopeExit&& o) noexcept : f_{std::move(o.f_)}, active_{o.active_} { o.active_ = false; } ~ScopeExit() noexcept { if (active_) f_(); } ScopeExit(const ScopeExit&) = delete; ScopeExit& operator=(const ScopeExit&) = delete; ScopeExit& operator=(ScopeExit&&) = delete; void release() noexcept { active_ = false; } void dismiss() noexcept { active_ = false; } [[nodiscard]] bool active() const noexcept { return active_; } private: F f_; bool active_{true}; }; // ── ScopeSuccess — runs only when scope exits normally (no exception) ───────── template class [[nodiscard]] ScopeSuccess { public: explicit ScopeSuccess(F f) noexcept(std::is_nothrow_move_constructible_v) : f_{std::move(f)}, exceptions_{std::uncaught_exceptions()} { } ~ScopeSuccess() noexcept { if (active_ && std::uncaught_exceptions() == exceptions_) f_(); } ScopeSuccess(const ScopeSuccess&) = delete; ScopeSuccess& operator=(const ScopeSuccess&) = delete; ScopeSuccess(ScopeSuccess&&) = delete; ScopeSuccess& operator=(ScopeSuccess&&) = delete; void release() noexcept { active_ = false; } void dismiss() noexcept { active_ = false; } private: F f_; int exceptions_; bool active_{true}; }; // ── ScopeFail — runs only when scope exits via exception ────────────────────── template class [[nodiscard]] ScopeFail { public: explicit ScopeFail(F f) noexcept(std::is_nothrow_move_constructible_v) : f_{std::move(f)}, exceptions_{std::uncaught_exceptions()} { } ~ScopeFail() noexcept { if (active_ && std::uncaught_exceptions() > exceptions_) f_(); } ScopeFail(const ScopeFail&) = delete; ScopeFail& operator=(const ScopeFail&) = delete; ScopeFail(ScopeFail&&) = delete; ScopeFail& operator=(ScopeFail&&) = delete; void release() noexcept { active_ = false; } void dismiss() noexcept { active_ = false; } private: F f_; int exceptions_; bool active_{true}; }; // ── Factory functions ───────────────────────────────────────────────────────── template [[nodiscard]] auto on_exit(F&& f) { return ScopeExit>{std::forward(f)}; } template [[nodiscard]] auto on_success(F&& f) { return ScopeSuccess>{std::forward(f)}; } template [[nodiscard]] auto on_fail(F&& f) { return ScopeFail>{std::forward(f)}; } // Aliases matching std::scope_{exit,success,failure} proposal naming. template [[nodiscard]] auto scope_exit(F&& f) { return on_exit(std::forward(f)); } template [[nodiscard]] auto scope_success(F&& f) { return on_success(std::forward(f)); } template [[nodiscard]] auto scope_failure(F&& f) { return on_fail(std::forward(f)); } } // namespace Void::Scope