class exit_scope { public: template< typename Callback > exit_scope( const Callback& callback ):caller_( new caller<Callback>(callback) ){} ~exit_scope(){ caller_->call(); delete caller_; } private: exit_scope(); exit_scope(const exit_scope&); exit_scope& operator =(const exit_scope&); struct caller_interface { virtual ~caller_interface(){} virtual void call()=0; }; template< typename Callback > struct caller: caller_interface { caller( const Callback& callback ): callback_(callback){} virtual void call(){ callback_(); } Callback callback_; }; caller_interface* caller_; };
int test() { std::string omega; std::cin >> omega; exit_scope guard1 = [&](){ std::cout<< "First exit scope "<<omega<<std::endl; }; return 0; }
#define EXIT_SCOPE_CREATE_UNIQ_NAME2(line) exit_scope_guard_##line #define EXIT_SCOPE_CREATE_UNIQ_NAME(line) EXIT_SCOPE_CREATE_UNIQ_NAME2(line) #define EXIT_SCOPE exit_scope EXIT_SCOPE_CREATE_UNIQ_NAME(__LINE__) = [&]()
int test1() { std::string omega; std::cin >> omega; EXIT_SCOPE{ std::cout << "Second exit scope" << omega<< std::endl; }; EXIT_SCOPE{ std::cout << "Third exit scope" << omega<<std::endl; }; return 0; }
class exit_scope { public: template< typename Callback > exit_scope( const Callback& callback ):callback_(callback){} ~exit_scope(){ callback_(); } private: exit_scope(); exit_scope(const exit_scope&); exit_scope& operator =(const exit_scope&); std::function<void(void)> callback_; };
int test1() { std::string omega; std::cin >> omega; BOOST_SCOPE_EXIT( (&omega) ) { std::cout << "Fourth exit scope" <<omega<< std::endl; } BOOST_SCOPE_EXIT_END return 0; }
Source: https://habr.com/ru/post/148534/
All Articles