FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Added `gsl::final_act` and `gsl::finally` · feiyunwill/cppfront@76c92e2 · GitHub

Commit 76c92e2

Browse files
committed
Added gsl::final_act and gsl::finally
1 parent b839468 commit 76c92e2

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

‎include/cpp2util.h‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,13 @@ constexpr auto as( std::optional<T> const& x ) -> auto&&
463463
using cpp2::cpp2_new;
464464

465465

466+
//-----------------------------------------------------------------------
467+
//
468+
// A partial implementation of GSL features Cpp2 relies on,
469+
// to keep this a standalone header without non-std dependencies
470+
//
471+
//-----------------------------------------------------------------------
472+
//
466473
namespace gsl {
467474

468475
//-----------------------------------------------------------------------
@@ -477,6 +484,46 @@ constexpr auto narrow_cast(From&& from) noexcept -> To
477484
return static_cast<To>(std::forward<From>(from));
478485
}
479486

487+
488+
//-----------------------------------------------------------------------
489+
//
490+
// An implementation of GSL's final_action and finally
491+
// (based on a PR I contributed to Microsoft GSL)
492+
//
493+
// final_action ensures something is run at the end of a scope
494+
//
495+
// finally is a convenience function to generate a final_action
496+
//
497+
//-----------------------------------------------------------------------
498+
//
499+
template <class F>
500+
class final_action
501+
{
502+
public:
503+
template <class FF>
504+
explicit final_action(FF&& ff) noexcept : f{std::forward<FF>(ff)} { }
505+
506+
~final_action() noexcept { if (invoke) f(); }
507+
508+
final_action(final_action&& other) noexcept
509+
: f(std::move(other.f)), invoke(std::exchange(other.invoke, false))
510+
{ }
511+
512+
final_action(const final_action& rhs) = delete;
513+
void operator=(const final_action&) = delete;
514+
void operator=(final_action&& other) = delete;
515+
516+
private:
517+
F f;
518+
bool invoke = true;
519+
};
520+
521+
template <class F>
522+
[[nodiscard]] auto finally(F&& f) noexcept
523+
{
524+
return final_action<F>{std::forward<F>(f)};
525+
}
526+
480527
}
481528

482529
#endif

0 commit comments

Comments
 (0)

Back | FazBrowse Home | New Git URL