fork download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. namespace gsl
  5. {
  6. //
  7. // GSL.util: utilities
  8. //
  9.  
  10. // index type for all container indexes/subscripts/sizes
  11. using index = std::ptrdiff_t;
  12.  
  13. // final_action allows you to ensure something gets run at the end of a scope
  14. template <class F>
  15. class final_action
  16. {
  17. public:
  18. explicit final_action(F f) noexcept : f_(std::move(f)) {}
  19.  
  20. final_action(final_action&& other) noexcept : f_(std::move(other.f_)), invoke_(other.invoke_)
  21. {
  22. other.invoke_ = false;
  23. }
  24.  
  25. final_action(const final_action&) = delete;
  26. final_action& operator=(const final_action&) = delete;
  27. final_action& operator=(final_action&&) = delete;
  28.  
  29. ~final_action() noexcept
  30. {
  31. if (invoke_) f_();
  32. }
  33.  
  34. private:
  35. F f_;
  36. bool invoke_{true};
  37. };
  38.  
  39. // finally() - convenience function to generate a final_action
  40. template <class F>
  41. final_action<F> finally(const F& f) noexcept
  42. {
  43. return final_action<F>(f);
  44. }
  45.  
  46. template <class F>
  47. final_action<F> finally(F&& f) noexcept
  48. {
  49. return final_action<F>(std::forward<F>(f));
  50. }
  51.  
  52. }
  53.  
  54. using namespace std;
  55.  
  56. void foo(bool & currState, bool newState)
  57. {
  58. auto revertState = gsl::finally([prevState = currState, &currState]{
  59. currState = prevState;
  60. });
  61. currState = newState;
  62. cout << "currState: " << currState << endl;
  63. }
  64.  
  65.  
  66. int main() {
  67. bool state = false;
  68. foo(state, true);
  69. cout << "state: " << state << endl;
  70. return 0;
  71. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
currState: 1
state: 0