Last active
August 29, 2015 14:12
-
-
Save codebrainz/70025dc52b7c4d156c05 to your computer and use it in GitHub Desktop.
A macro/template implementation of C++ scope guard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <utility> | |
namespace ScopeExitNamespace__ { | |
template<typename T> struct OnScopeExit__ { | |
T func; | |
OnScopeExit__(T func) : func(std::move(func)) {} | |
~OnScopeExit__() noexcept { func(); } | |
}; | |
} | |
#define scope_exit__(id, code) \ | |
auto scope_exit_function_##id##__ = [&](){code;}; \ | |
ScopeExitNamespace__::OnScopeExit__<decltype(scope_exit_function_##id##__)> \ | |
scope_exit_cleanup_##id##__(std::move(scope_exit_function_##id##__)) | |
#define scope_exit(code) scope_exit__(__COUNTER__, code) | |
// #include <iostream> | |
// int main() | |
// { | |
// scope_exit(std::cout << "done" << std::endl); | |
// std::cout << "Running..."; | |
// return 0; | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment