SUNphi  1.0
SingleInstance.hpp
Go to the documentation of this file.
1 #ifndef _SINGLE_INSTANCE_HPP
2 #define _SINGLE_INSTANCE_HPP
3 
4 #include <debug/MinimalCrash.hpp>
5 #include <metaprogramming/StaticMemberWithInitializator.hpp>
6 
7 /// \file SingleInstance.hpp
8 ///
9 /// \brief Defines a simple class, with a counter wich enable only one
10 /// instance at the time
11 
12 namespace SUNphi
13 {
14  /// Single Instance enforcer class
15  ///
16  /// To enforce a class to be instantiated at most once, inherit this
17  /// class. Example:
18  ///
19  /// \code
20  /// class A :
21  /// public SingleInstance<A>
22  /// {
23  /// };
24  ///
25  /// A a1; // ok
26  /// A a2; // error!
27  /// \endcode
28  template <typename T> // Type from which to inherit, to distinguish each count
30  {
31 
32  PROVIDE_STATIC_MEMBER_WITH_INITIALIZATOR(int,count,0,Counter of instances);
33 
34  /// Check that no instance exists
36  {
37  if(count()!=0)
38  MINIMAL_CRASH("Count is not zero: %d",count());
39  }
40 
41  public:
42 
43  /// Constructor, checking no instance exists before
45  {
47 
48  count()++;
49  }
50 
51  /// Destructor, checking that no instance exists at the end
53  {
54  count()--;
55 
57  }
58  };
59 }
60 
61 #endif
#define MINIMAL_CRASH(...)
Initialize the minimal crasher.
#define PROVIDE_STATIC_MEMBER_WITH_INITIALIZATOR(T, NAME, VALUE, DESCRIPTION)
SingleInstance()
Constructor, checking no instance exists before.
void crashIfInstancesExists()
Check that no instance exists.
~SingleInstance()
Destructor, checking that no instance exists at the end.