Created
February 12, 2015 07:24
-
-
Save gruzovator/6e00ae1e09b4424c8f6a to your computer and use it in GitHub Desktop.
c++11 scope exit
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
/** Scope exit */ | |
template<typename Callable> | |
class ScopeExit | |
{ | |
Callable m_callable; | |
public: | |
explicit ScopeExit(Callable c) : m_callable(c) {} | |
ScopeExit(const ScopeExit&) = delete; | |
~ScopeExit() { m_callable(); } | |
}; | |
/** | |
MACRO Magic to avoid typeing: | |
auto code_uniqueid = []{}; | |
ScopeExit<decltype(code_unqiueid)>{code_uniqueid}; | |
*/ | |
#define CONCATENATE_DETAIL_20150212(x, y) x##y | |
#define CONCATENATE_20150212(x, y) CONCATENATE_DETAIL_20150212(x, y) | |
#define SCOPE_EXIT(code) auto CONCATENATE_20150212(code_,__LINE__) = code;\ | |
ScopeExit<decltype(CONCATENATE_20150212(code_,__LINE__))>\ | |
CONCATENATE_20150212(scope_exit_,__LINE__)(CONCATENATE_20150212(code_,__LINE__)) | |
#include <iostream> | |
using namespace std; | |
int main(int argc, char const *argv[]) | |
{ | |
SCOPE_EXIT([]{cout << "cleanup1" << endl;}); | |
SCOPE_EXIT([]{cout << "cleanup2" << endl;}); | |
cout << "running.." << endl; | |
return 0; | |
} | |
/* After preprocessor: | |
int main(int argc, char const *argv[]) | |
{ | |
auto code_32 = []{cout << "cleanup1" << endl;}; ScopeExit<decltype(code_32)> scope_exit_32(code_32); | |
auto code_33 = []{cout << "cleanup2" << endl;}; ScopeExit<decltype(code_33)> scope_exit_33(code_33); | |
cout << "running.." << endl; | |
return 0; | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment