0

I am trying to implement template singleton pattern but I got the following error. How should I overcome this error?

Below is singleton_template.h

#include <iostream>
#include <string>
/*
* Burada yapılan herşey ".h" dosyası içerinde olmalı
*/
template<typename T>
class Singleton
{
private:
   static T* _instance;
   Singleton(const Singleton&);
   Singleton & operator=(const Singleton& rhs);

protected:
   Singleton();

public:
   static T* getInstance()
   {
     if(!_instance)
     _instance = new T;
     return _instance;
   }

   void destroyInstance()
   {
       delete _instance;
       _instance = NULL;
   }
};

template<typename T>
T* Singleton<T>::_instance= NULL;

Here is the singleton_template.cpp

#include <iostream>
#include <string>
#include "singleton_template.h"

class GKM : public Singleton<GKM>
{
public:

  GKM()
  {
    std::cout << "Single GKM created"<<std::endl;
  }
  virtual void initialize(){return;}

};

class Turnstile: public GKM 
{
public:
  Turnstile(){std::cout << "Single turnstile created add: "<< this<<std::endl;}
  virtual void initialize(){std::cout <<"Turnstile"<< std::endl;}

};

int main()
{
  GKM* trn= Turnstile::getInstance();
  trn->initialize();
  return 0;
}

Here is what I get after a failed compilation:

/tmp/ccfD0Xgx.o: In function GKM::GKM(): singleton_template.cpp:(.text._ZN3GKMC2Ev[_ZN3GKMC5Ev]+0xd): undefined reference to Singleton<GKM>::Singleton() collect2: error: ld returned 1 exit status

Maksim Solovjov
  • 3,147
  • 18
  • 28
Nuri
  • 1
  • 1

1 Answers1

1

You did not implement the default constructor for Singleton class, which you need because you subclass the Singleton class. You can change the

Singleton();

line to

Singleton() {}

However, as I read your code, it will not anyway work as expected, because

GKM* trn= Turnstile::getInstance();

actually creates only GKM object, not Turnstile, because you have the Singleton templated on GKM, not on Turnstile. (Or was this intended?)

Petr
  • 9,812
  • 1
  • 28
  • 52
  • Thank you Petr, soon it compiles. As you mentioned it just created `GKM`. How do i create single `turnstile` object from `GKM` class – Nuri Sep 15 '15 at 12:10
  • @Nuri, there are many (or no) ways to create a `Turnstile` from a `GKM` object, depending on what exactly you want to achieve. I suggest that you ask a separate question describing what actually you want to achieve (not just "create a `Turnstile` from a `GKM`", but why do you really need this for, why are you trying to use a singleton after all, what do you want to have in your program). – Petr Sep 15 '15 at 12:13