Created
March 7, 2012 20:32
-
-
Save nmandery/1995912 to your computer and use it in GitHub Desktop.
Go-like defer statement (C++11)
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
/** | |
* Go-like defer statement (C++11) | |
* | |
* g++ --std=c++0x -o def def.cc | |
* | |
* also see http://blog.korfuri.fr/post/go-defer-in-cpp/ | |
*/ | |
#include <functional> | |
#include <iostream> | |
#define DEFER_UQ(A, UQID) defer defr_ ##UQID ([]{ A;}); | |
#define DEFER_CALL(A, UQ) DEFER_UQ(A, UQ) | |
#ifdef __COUNTER__ | |
#define DEFER(A) DEFER_CALL(A, __COUNTER__) | |
#else | |
#define DEFER(A) DEFER_CALL(A, __LINE__) | |
#endif | |
class defer { | |
std::function<void()> t; | |
public: | |
defer(std::function<void()> &&t) : t(t) {} | |
~defer() { t(); } | |
}; | |
int main() { | |
defer d([]{ std::cout << " world!!" << std::endl; }); | |
DEFER(std::cout << "... and again" << std::endl) | |
DEFER(std::cout << "... plus once more." << std::endl) | |
std::cout << "Hello"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awful for efficiency - std::function<> does type erasure via heap allocations. Salty syntax.