Created
April 2, 2019 06:27
-
-
Save SaitoAtsushi/c40f4facd5754502136010fdf14228d0 to your computer and use it in GitHub Desktop.
Go の defer っぽいものを C++ でやってみる遊び
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
#include <functional> | |
class defer_t { | |
private: | |
std::function<void(void)> f; | |
public: | |
defer_t(std::function<void(void)> f); | |
~defer_t(void); | |
}; | |
defer_t::defer_t(std::function<void(void)> f) : f(f) {} | |
defer_t::~defer_t(void) { f(); } | |
#define defer_helper2(line) defer_tmp ## line | |
#define defer_helper(line) defer_helper2(line) | |
#define defer(x) auto defer_helper(__LINE__) = defer_t([&](void){x}); | |
/* | |
https://qiita.com/joji/items/b933b03bc30b26848d19 | |
を元にした使用例 | |
*/ | |
#include <iostream> | |
void test(void) { | |
defer( std::cout << "test world" << std::endl; ) | |
} | |
void test2(){ | |
defer( std::cout << "test2 world" << std::endl; ) | |
} | |
int main(void) { | |
defer( std::cout << "world1" << std::endl; ) | |
defer( std::cout << "world2" << std::endl; ) | |
test(); | |
test2(); | |
std::cout << "world" << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment