Util--  1.1
auto_flag.hh
Go to the documentation of this file.
1 #ifndef UTILMM_AUTOFLAG_H
2 #define UTILMM_AUTOFLAG_H
3 
4 #include <boost/noncopyable.hpp>
5 
6 namespace utilmm
7 {
10  template<typename T>
11  class auto_flag
12  : private boost::noncopyable
13  {
14  int& m_field;
15  int m_mask;
16  bool m_restore;
17 
18  public:
19  auto_flag(int& field, int mask, bool value = true, bool restore_old = true)
20  : m_field(field), m_mask(mask)
21  , m_restore(restore_old ? get() : !value)
22  {
23  set(value);
24  }
25 
26  ~auto_flag() { set(m_restore); }
27 
28  bool get() { return (m_field & m_mask) == m_mask; }
29  void set(bool value)
30  { m_field = (m_field & ~m_mask) | (m_mask * static_cast<int>(value)); }
31 
32 
33  };
34 
35  template<>
36  class auto_flag<bool>
37  : private boost::noncopyable
38  {
39  bool& m_flag;
40  bool m_restore;
41 
42  // Safe bool idiom
43  struct safe_bool_struct
44  { void method(); };
45  typedef void (safe_bool_struct::*safe_bool)();
46 
47  public:
52  auto_flag(bool& flag, bool init = true, bool restore_old = true)
53  : m_flag(flag), m_restore(restore_old ? flag : !init)
54  { m_flag = init; }
55 
59  ~auto_flag() { m_flag = m_restore; }
60 
63  bool get() const { return m_flag; }
64 
65  operator safe_bool() const { return m_flag ? &safe_bool_struct::method : 0; }
66  };
67 
68 }
69 
70 #endif
71 
~auto_flag()
Definition: auto_flag.hh:26
Definition: auto_flag.hh:11
auto_flag(bool &flag, bool init=true, bool restore_old=true)
Definition: auto_flag.hh:52
Definition: auto_flag.hh:6
bool get()
Definition: auto_flag.hh:28
auto_flag(int &field, int mask, bool value=true, bool restore_old=true)
Definition: auto_flag.hh:19
~auto_flag()
Definition: auto_flag.hh:59

Generated on Mon Oct 8 2018 08:38:45 for Util-- by doxygen 1.8.11
SourceForge.net Project Page