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(); }
posted @ 2024-10-12 10:09  joel-q  阅读(4)  评论(0编辑  收藏  举报