Upgrade the existing scope exit utility

This commit is contained in:
Celtic Minstrel 2021-04-02 16:31:16 -04:00 committed by Celtic Minstrel
parent e3838ccaa5
commit 72cede2c8a
3 changed files with 24 additions and 6 deletions

View file

@ -306,7 +306,9 @@ bool mp_join_game::show_flg_select(int side_num, bool first_time)
{
gui2::dialogs::faction_select flg_dialog(flg, color, side_num);
flg_dialog_ = &flg_dialog;
utils::scope_exit se([this]() { flg_dialog_ = nullptr; });
ON_SCOPE_EXIT(this) {
flg_dialog_ = nullptr;
};
if(!flg_dialog.show() && !first_time) {
return true;

View file

@ -817,7 +817,9 @@ void unit_recruited(const map_location& loc,const map_location& leader_loc)
unit_animator animator;
{
utils::scope_exit se([u] () { u->set_hidden(false); });
ON_SCOPE_EXIT(u) {
u->set_hidden(false);
};
u->set_hidden(true);
if (leader_visible && unit_visible) {

View file

@ -14,15 +14,29 @@
#pragma once
#include <functional>
#include <boost/preprocessor/cat.hpp>
namespace utils {
template<typename F>
class scope_exit {
//TODO: with c++17 we could make this a template class with 'F f_' instead of 'std::function<void ()> f_';
std::function<void ()> f_;
F f_;
public:
explicit scope_exit(F&& f) : f_(std::forward<F>(f)) {}
~scope_exit() { f_(); }
};
struct scope_exit_syntax_support {
template<typename F>
explicit scope_exit(F&& f) : f_(f) {}
~scope_exit() { if(f_) { f_(); }}
scope_exit<F> operator<<(F&& f) {
return scope_exit<F>(std::forward<F>(f));
}
};
} // namespace utils
/**
* Run some arbitrary code (a lambda) when the current scope exits
* The lambda body follows this header, terminated by a semicolon.
* @arg ... Capture clause for the lambda.
*/
#define ON_SCOPE_EXIT(...) [[maybe_unused]] const auto& BOOST_PP_CAT(scope_exit, __LINE__) = utils::scope_exit_syntax_support() << [__VA_ARGS__]()