-
Notifications
You must be signed in to change notification settings - Fork 0
/
auto_closer.h
62 lines (53 loc) · 1.13 KB
/
auto_closer.h
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
62
/* THOR - THOR Template Library
* Joshua M. Kriegshauser
*
* auto_closer.h
*
* Template class for automatically closing resources (i.e. Windows HANDLE objects, etc)
*/
#ifndef THOR_AUTO_CLOSER_H
#define THOR_AUTO_CLOSER_H
#pragma once
#ifndef THOR_BASETYPES_H
#include "basetypes.h"
#endif
namespace thor
{
namespace internal
{
template<class T, T INVALID, typename T_CLOSEFUNC> class auto_closer
{
THOR_DECLARE_NOCOPY(auto_closer);
struct wrapper : public T_CLOSEFUNC
{
T t_;
wrapper(T t) : t_(t) {};
wrapper(T t, T_CLOSEFUNC func) : T_CLOSEFUNC(func), t_(t) {}
} wrapper_;
public:
auto_closer(T t) : wrapper_(t) {}
auto_closer(T t, T_CLOSEFUNC func) : wrapper_(t, func) {}
~auto_closer()
{
close();
}
void close()
{
if (wrapper_.t_ != INVALID)
{
static_cast<T_CLOSEFUNC&>(wrapper_)(wrapper_.t_);
wrapper_.t_ = INVALID;
}
}
bool valid() const
{
return wrapper_.t_ != INVALID;
}
operator T () const
{
return wrapper_.t_;
}
};
} // namespace internal
} // namespace thor
#endif