-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathscoped.hpp
62 lines (47 loc) · 1.38 KB
/
scoped.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
//----------------------------------------
// utils::scoped: C++11-based scope guard
//----------------------------------------
//
// Copyright kennytm (auraHT Ltd.) 2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file doc/LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
/**
``<utils/scoped.hpp>`` --- C++11-based scope guard
==================================================
This module implements the :macro:`utils::make_scope_guard` function for
generating a scope guard using a lambda function.
Synopsis
--------
::
{
FILE* f = fopen("file.txt", "rb");
auto f_guard = utils::make_scope_guard([&]{ fclose(f); });
...
// the file 'f' will be closed when exiting the scope.
}
*/
#ifndef SCOPED_HPP_I40D5JT8OZ9
#define SCOPED_HPP_I40D5JT8OZ9 1
#include <type_traits>
#include <utility>
namespace utils {
namespace xx_impl
{
template <typename F>
class scope_guard final
{
typename std::remove_reference<F>::type destructor;
public:
scope_guard(F&& destructor) : destructor(std::move(destructor)) {}
~scope_guard() { destructor(); }
};
}
template <typename F>
const xx_impl::scope_guard<F> make_scope_guard(F&& f)
noexcept(noexcept(F(std::declval<F&&>())))
{
return xx_impl::scope_guard<F>(std::forward<F>(f));
}
}
#endif