OSDN Git Service

instance_counter のコメントを微修正
[gintenlib/gintenlib.git] / gintenlib / instance_counter.hpp
1 #ifndef GINTENLIB_INCLUDED_INSTANCE_COUNTER_HPP_
2 #define GINTENLIB_INCLUDED_INSTANCE_COUNTER_HPP_
3
4 /*
5
6       <gintenlib/instance_counter.hpp>
7
8   instance_counter : オブジェクトの存在個数を数える
9
10   宣言:
11     // 存在する Derived の数を数える
12     template<typename Derived>
13     struct instance_counter
14     {
15       static int use_count();
16       
17      protected:
18       instance_counter();
19       instance_counter( const instance_counter& );
20       ~instance_counter() throw ();
21       
22     };  // instance_counter<Derived>
23     
24     template<typename Derived>
25     int count_instances();
26
27   機能:
28     struct hoge : gintenlib::instance_counter<hoge>
29     {
30       // 実装
31     }
32     のように使うことで、 hoge の有効なインスタンス数を数え上げます。
33
34 */
35
36 #include "enable_if.hpp"
37
38 #include <boost/mpl/assert.hpp>
39 #include <boost/type_traits/is_base_of.hpp>
40
41 namespace gintenlib
42 {
43  namespace instance_counter_  // ADL回避用
44  {
45   // 存在する Derived の数を数える
46   template<typename Derived>
47   struct instance_counter
48   {
49     static int use_count()
50     {
51       // きちんと継承関係にあるかチェック
52       BOOST_MPL_ASSERT(( boost::is_base_of<instance_counter, Derived> ));
53       
54       return count_;
55     }
56     
57    protected:
58     instance_counter()
59     {
60       ++count_;
61     }
62     instance_counter( const instance_counter& )
63     {
64       ++count_;
65     }
66     ~instance_counter() throw ()
67     {
68       --count_;
69     }
70     
71    private:
72     static int count_;
73     
74   };  // instance_counter<Derived>
75   
76   // 実体の確保(テンプレートなのでヘッダファイルに置ける)
77   template<typename Derived>
78   int instance_counter<Derived>::count_ = 0;
79   
80   // フリー関数版
81   template<typename Derived>
82   inline typename enable_if< boost::is_base_of< instance_counter<Derived>, Derived >, int >::type
83     count_instances()
84   {
85     return instance_counter<Derived>::use_count();
86   }
87  
88  }  // namespace instance_counter_
89  
90   // gintenlib 名前空間に引き入れる
91   using namespace instance_counter_;
92
93 }   // namespace gintenlib
94
95 #endif  // #ifndef GINTENLIB_INCLUDED_INSTANCE_COUNTER_HPP_