From 91606850fdbea8a9c6d919b7ad90bd6643676f30 Mon Sep 17 00:00:00 2001 From: Maxime Coste Date: Tue, 20 Dec 2011 19:18:00 +0000 Subject: [PATCH] Utils: add on_scope_end utility on_scope_end permits to register a functor to be called at scope end (either exception thrown or normal scope end). this is usefull for cleanup code that must be run. usage: auto cleaner = on_scope_end([]() { cleanup(); }); --- src/utils.hh | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/utils.hh b/src/utils.hh index 5a46b4fd..6a196053 100644 --- a/src/utils.hh +++ b/src/utils.hh @@ -112,6 +112,21 @@ inline std::string str_to_str(const std::string& str) return str; } +template +class OnScopeEnd +{ +public: + OnScopeEnd(T func) : m_func(func) {} + ~OnScopeEnd() { m_func(); } +private: + T m_func; +}; + +template +OnScopeEnd on_scope_end(T t) +{ + return OnScopeEnd(t); +} }