Skip to content

Instantly share code, notes, and snippets.

@tomilov
Last active October 11, 2016 05:15
Show Gist options
  • Save tomilov/92904424b6950bb343170d3279afa17b to your computer and use it in GitHub Desktop.
Save tomilov/92904424b6950bb343170d3279afa17b to your computer and use it in GitHub Desktop.
#include <utility>
template< std::size_t I, typename F >
struct wrapper { F f; };
template< std::size_t I, typename F >
constexpr
F &
get(wrapper< I, F > * sg) noexcept
{
return sg->f;
}
template< typename index_sequence, typename ...F >
struct scope_guard_base;
template < std::size_t ...I, typename ...F >
struct scope_guard_base< std::index_sequence< I... >, F... >
: wrapper< I, F >...
{
using base = scope_guard_base;
scope_guard_base(F &... f) : wrapper< I, F >{std::forward< F >(f)}... { ; }
~scope_guard_base() { (get< (sizeof...(I) - 1 - I) >(this)(), ...); }
};
template< typename ...F >
struct scope_guard
: scope_guard_base< std::index_sequence_for< F... >, F... >
{
scope_guard(F &&... f) : scope_guard::base(f...) { ; }
};
#include <iostream>
template< std::size_t I >
struct F
{
F() { std::cout << I << std::endl; }
void operator () () const { std::cout << I << std::endl; }
};
int main()
{
F< 0 > const f{};
scope_guard _{f, F< 1 >{}, F< 2 >{}};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment