Created
October 2, 2015 19:40
-
-
Save r-lyeh-archived/3b35e5f7a47b96f991cd to your computer and use it in GitHub Desktop.
defer 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
// src: http://www.gingerbill.org/article/defer-in-cpp.html | |
// This code requires C++11 features such as move semantics | |
#pragma once | |
#include <functional> | |
namespace Impl | |
{ | |
template <typename Func> | |
struct Defer | |
{ | |
Func func; | |
Defer(Func&& func) | |
: func(std::forward<Func>(func)) | |
{ | |
} | |
~Defer() | |
{ | |
func(); | |
} | |
}; | |
template <typename Func> | |
Defer<Func> deferFunc(Func&& func) | |
{ | |
return Defer<Func>(std::forward<Func>(func)); | |
} | |
#define DEFER_1(x, y) x##y | |
#define DEFER_2(x, y) DEFER_1(x, y) | |
#define DEFER_3(x) DEFER_2(x, __COUNTER__) | |
#define defer(code) auto DEFER_3(_defer_) = Impl::deferFunc([&](){code;}); | |
} // namespace Impl | |
/* | |
// example: | |
void someFunc() | |
{ | |
FILE* file = fopen("filename.ext", "rb"); | |
if (file == nullptr) | |
return; | |
defer(fclose(file)); | |
u8* buffer = (u8*)allocate(64 * sizeof(u8)); | |
if (buffer == nullptr) | |
return; // fclose is called automatically | |
defer(deallocate(buffer)); | |
defer({ | |
printf("You can even defer "); | |
printf("an entire block too!"); | |
}); | |
// Do whatever... | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment