defer :)
This commit is contained in:
parent
6a465c5d59
commit
d985865048
21
src/defer.h
Normal file
21
src/defer.h
Normal file
@ -0,0 +1,21 @@
|
||||
#ifndef DEFER_H
|
||||
#define DEFER_H
|
||||
|
||||
#include <functional>
|
||||
#include <iostream>
|
||||
|
||||
class Defer {
|
||||
public:
|
||||
Defer(std::function<void()> func) : func_(func) {}
|
||||
~Defer() { func_(); }
|
||||
|
||||
private:
|
||||
std::function<void()> func_;
|
||||
};
|
||||
|
||||
#define CONCAT_IMPL(a, b) a##b
|
||||
#define CONCAT(a, b) CONCAT_IMPL(a, b)
|
||||
|
||||
#define DEFER(code) Defer CONCAT(defer__, __LINE__)([&]() { code; });
|
||||
|
||||
#endif // DEFER_H
|
11
src/main.cpp
11
src/main.cpp
@ -1,6 +1,15 @@
|
||||
#include "defer.h"
|
||||
#include <iostream>
|
||||
|
||||
struct Meep {
|
||||
std::string foo = "Meep!";
|
||||
};
|
||||
|
||||
int main() {
|
||||
std::cout << "Hello, World!" << std::endl;
|
||||
Meep *meep = new Meep();
|
||||
DEFER(delete meep);
|
||||
|
||||
DEFER(std::cout << "Goodbye, " << meep->foo << std::endl);
|
||||
std::cout << "Hello, " << meep->foo << std::endl;
|
||||
return 0;
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user