Created
June 14, 2022 17:22
-
-
Save vladiant/868b443f1308dadad654c9fa7476b174 to your computer and use it in GitHub Desktop.
C++ Finally
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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