fork download
  1. #include <iostream>
  2. #include <utility>
  3.  
  4. #define PP_CAT(a, b) PP_CAT_I(a, b)
  5. #define PP_CAT_I(a, b) a ## b
  6.  
  7. // 普通はいらない
  8. template<typename F>
  9. struct scope_exit_t {
  10. scope_exit_t(F & f) : f(f) {}
  11. ~scope_exit_t() { std::cout << "by lvalue: "; f(); }
  12. private:
  13. F & f;
  14. };
  15.  
  16. template<typename F>
  17. struct scope_exit_t<F&&> {
  18. scope_exit_t(F && f) : f(f) {}
  19. ~scope_exit_t() { std::cout << "by rvalue: "; f(); }
  20. private:
  21. F f;
  22. };
  23.  
  24. struct scope_exit_helper {
  25. template<typename F>
  26. scope_exit_t<F&&> operator->*(F && f) const {
  27. return scope_exit_t<F&&>(std::forward<F>(f));
  28. }
  29. };
  30.  
  31. #define scope_exit auto PP_CAT(scope_exit_, __LINE__) = scope_exit_helper() ->* [&] ()
  32.  
  33. int main() {
  34. scope_exit { std::cout << "hogehoge\n"; };
  35. scope_exit { std::cout << "piyopiyo\n"; };
  36. }
  37.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty