1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class defer : std::shared_ptr<defer> { public: template <class function_tt, class... args_tt> explicit defer(function_tt &&func, args_tt &&...args) : std::shared_ptr<defer>( nullptr, [func = std::forward<function_tt>(func), ...args = std::forward<args_tt>(args)](defer *) mutable { std::invoke(std::forward<function_tt>(func), std::forward<args_tt>(args)...); }) {} };
int main(int argc, char *argv[]) { { int x = 1; { defer def( [&](int, int) { std::cout << x << "\n"; x = 10; }, 1, 2); } std::cout << x << std::endl; } }
|