tags:

views:

79

answers:

3

Hi,

We have a singleton template class as defines below

  template<class T> class Singleton{

     T& reference(){
       return objT;
    }

    private:
     T objT;

    };

And another user defined class which uses this singleton

   class TestClass{

    static Singleton<TestClass> instance;

    static TestClass * getPointer()
    {
      return &instance.objT;
    }


   private:
     TestClass(){}
   };

   template<TestClass>
    Singleton<TestClass> TestClass::instance;

On compilation with GCC we are getting the error

In function static_initialization_and_destruction undefined reference to Singleton::Singleton().

What can be the reason for this.

A: 
static Singleton<TestClass> instance;

you are actually trying to create an instance of class Singleton in above line; which will look for default constructor Singleton() (which is already present as you haven't explicitly defined it private).

T& reference() is a private method in your class.

And I didn't really understand this

 template<TestClass>
    Singleton<TestClass> TestClass::instance;

Are you sure what you are trying to do? Cause am not ;)

Maybe you want to read this to understand what you are doing http://www.yolinux.com/TUTORIALS/C++Singleton.html

Kedar
@Kedar As instance is static variable, I need to declare it outside the class
siri
It looks you really don't want to use singleton here.
Kedar
A: 

Easiest fix: Don't use a singleton.

DeadMG
But this code compiles properly with VS Compiler
siri
@siri: Congrats, you got a bad design pattern to compile.
DeadMG
+1  A: 

Ignoring the fact, that in your example there is no need for Singleton template, consider this simplified example (I am using structs to avoid access issues):

template <class T> 
struct Singleton
{
    T object;
};

struct TestClass;
typedef Singleton<TestClass> TCS;

TCS test1;            // not ok, no definition of TestClass available;

struct TestClass
{
    TestClass(){}
    static TCS test2; // not ok, no definition of TestClass available;
};

TCS test3;            // ok, TestClass is defined;

To declare a member of type T, you need a complete definition of this type T. So, test1 and test2 are not legal - there is only a declaration, not definition of T. On the contrary, test3 is legal - it is located after the complete definition of the class. Easiest fix here is to use pointer to type - to declare a pointer to type T, you need a declaration instead of definition for the type T:

template <class T> 
struct Singleton
{
    T * object;
};
SadSido