10#include <userver/utils/assert.hpp>
12USERVER_NAMESPACE_BEGIN
19 virtual ~ScopeBase() =
default;
21 virtual void AfterConstruction() = 0;
24template <
typename Handle>
25class Scope
final :
public ScopeBase {
27 using AfterConstructionCallback = std::function<Handle()>;
29 explicit Scope(AfterConstructionCallback after_construction)
30 : after_construction_(std::move(after_construction))
33 void AfterConstruction()
override { before_destruction_.emplace(after_construction_()); }
36 AfterConstructionCallback after_construction_;
37 std::optional<Handle> before_destruction_;
41class Scope<
void>
final :
public ScopeBase {
43 using AfterConstructionCallback = std::function<
void()>;
45 explicit Scope(AfterConstructionCallback after_construction)
46 : after_construction_(std::move(after_construction))
49 void AfterConstruction()
override { after_construction_(); }
52 AfterConstructionCallback after_construction_;
61using ScopePtr = std::unique_ptr<impl::ScopeBase>;
68template <
typename AfterConstructionCallback>
69ScopePtr
MakeScope(AfterConstructionCallback after_construction)
71 using Handle = std::invoke_result_t<AfterConstructionCallback>;
72 return std::make_unique<impl::Scope<Handle>>(std::move(after_construction));