--- /dev/null
+#ifndef GINTENLIB_INCLUDED_INSTANCE_COUNTER_HPP_
+#define GINTENLIB_INCLUDED_INSTANCE_COUNTER_HPP_
+
+/*
+
+ <gintenlib/instance_counter.hpp>
+
+ instance_counter : オブジェクトの存在個数を数える
+
+ 宣言:
+ // 存在する Derived の数を数える
+ template<typename Derived>
+ struct instance_counter
+ {
+ static int use_count();
+
+ protected:
+ instance_counter();
+ instance_counter( const instance_counter& );
+ ~instance_counter() throw ();
+
+ }; // instance_counter<Derived>
+
+ template<typename Derived>
+ int count_instances();
+
+ 機能:
+ struct hoge : gintenlib::instance_counter<hoge>
+ {
+ // 実装
+ }
+ のように使うことで、 hoge の有効なインスタンス数を数え上げます。
+
+*/
+
+#include "enable_if.hpp"
+
+#include <boost/mpl/assert.hpp>
+#include <boost/type_traits/is_base_of.hpp>
+
+namespace gintenlib
+{
+ namespace instance_counter_ // ADL回避用
+ {
+ // 存在する Derived の数を数える
+ template<typename Derived>
+ struct instance_counter
+ {
+ static int use_count()
+ {
+ // きちんと継承関係にあるかチェック
+ BOOST_MPL_ASSERT(( boost::is_base_of<instance_counter, Derived> ));
+
+ return count_;
+ }
+
+ protected:
+ instance_counter()
+ {
+ ++count_;
+ }
+ instance_counter( const instance_counter& )
+ {
+ ++count_;
+ }
+ ~instance_counter() throw ()
+ {
+ --count_;
+ }
+
+ private:
+ static int count_;
+
+ }; // instance_counter<Derived>
+
+ // 実体の確保(テンプレートなのでソースファイルに置ける)
+ template<typename Derived>
+ int instance_counter<Derived>::count_ = 0;
+
+ // フリー関数版
+ template<typename Derived>
+ inline typename enable_if< boost::is_base_of< instance_counter<Derived>, Derived >, int >::type
+ count_instances()
+ {
+ return instance_counter<Derived>::use_count();
+ }
+
+ } // namespace instance_counter_
+
+ // gintenlib 名前空間に引き入れる
+ using namespace instance_counter_;
+
+} // namespace gintenlib
+
+#endif // #ifndef GINTENLIB_INCLUDED_INSTANCE_COUNTER_HPP_