Skip to content

Instantly share code, notes, and snippets.

@vladiant
Created June 14, 2022 17:22
Show Gist options
  • Save vladiant/868b443f1308dadad654c9fa7476b174 to your computer and use it in GitHub Desktop.
Save vladiant/868b443f1308dadad654c9fa7476b174 to your computer and use it in GitHub Desktop.
C++ Finally
#include <functional>
#include <iostream>
// https://www.youtube.com/watch?v=eG5suWcHI8M
// Lightning Talk: FINALLY - The Presentation You've All Been Waiting For - Louis Thomas - CppCon 2021
class Finally {
public:
std::function<void()> m_action;
explicit Finally(std::function<void()> action)
: m_action(std::move(action)) {}
~Finally() { m_action(); }
};
int main() {
Finally test([]() { std::cout << "Done.\n"; });
return 0;
}
#include <iostream>
template <typename ActionT>
class Finally {
public:
ActionT m_action;
explicit Finally(ActionT action) : m_action(std::move(action)) {}
~Finally() { m_action(); }
};
int main() {
Finally test([]() { std::cout << "Done.\n"; });
return 0;
}
#include <iostream>
template <typename Fn>
auto Finally(Fn action) {
class FinallyImpl {
public:
Fn m_action;
explicit FinallyImpl(Fn action) : m_action(std::move(action)) {}
~FinallyImpl() { m_action(); }
};
return FinallyImpl(std::move(action));
}
int main() {
// FILE* f = fopen(...)
// auto close_f = Finally([&f]{ fclose(f); });
auto test = Finally([]() { std::cout << "Done.\n"; });
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment