Singletonクラスの継承

仕事で似たようなレジスタ管理クラスを複数作る必要があって,
うまいことSIngletonパターンをのせたベースクラスを継承して
使いたいなと思っていましたが,やり方を知りませんでした.

テンプレート化するとよいんですね.

timlibの作者さんのページを参考に.
C++ の Singleton パターンを Template 化 | TM Life

というわけで,ベースクラスとその継承を書いたサンプルを作りました.
http://gist.github.com/glass5er/5813190

(以下,2013/6/30時点でのサンプルコードのコピペ)

#include <iostream>
#include <string>
 
using namespace std;
 
//----------------
 
template <class U>
class SingletonParent
{
  public:
    static U* getInstance() {
      static U instance;
      return &instance;
    }
 
  protected:
    //--  template func in template class available
    template<typename T> void print2Times(T v);
 
    SingletonParent() {
      base_str = string("BASE");
    }
    virtual ~SingletonParent() {}
    string base_str;
};
 
 
//--  use template succession
class SingletonChild : public SingletonParent<SingletonChild> {
  public:
    SingletonChild() {
      child_value = 0;
    }
    ~SingletonChild() {}
 
    void set(int v) { child_value = v; }
    int  get()      { return child_value; }
 
    void print()    {
      print2Times(base_str);
      print2Times(child_value);
    }
  private:
    int child_value;
};
 
//--  when defining template func in template class,
//--  2 template declaraton required
template<class U> template<typename T>
void
SingletonParent<U>::print2Times(T v)
{
  cout << v << v << endl;
}
 
 
//----------------
 
 
int
main(int argc, char const* argv[])
{
  //--  actually the same instance
  SingletonChild *inst1 = SingletonChild::getInstance();
  SingletonChild *inst2 = SingletonChild::getInstance();
 
  //--  both 0
  cout << inst1->get() << endl;
  cout << inst2->get() << endl;
 
  //--  BASEBASE, 00
  inst1->print();
 
  inst2->set(3);
 
  //--  both 3
  cout << inst1->get() << endl;
  cout << inst2->get() << endl;
 
  //--  BASEBASE, 33
  inst1->print();
  return 0;
}