tour cpp: 实现 defer或者说on_exit
c++17
#include <iostream>
template <class Func>
struct FinalAction {
explicit FinalAction(Func f) : act(f) {}
~FinalAction() { act(); }
Func act;
};
template <class Func>
[[nodiscard]] auto defer(Func f) {
return FinalAction{f};
}
void foo() {
using namespace std;
auto deferred = defer([]() { cout << "deferred" << endl; });
cout << "do something" << endl;
}
int main() { foo(); }