Template linking problem

Harvey Chapman hchapman-gcc-help@3gfp.com
Wed Nov 7 15:26:00 GMT 2007


On Nov 7, 2007, at 7:44 AM, John Love-Jensen wrote:

> Your Singleton class forward declares a "static Type* ptr", but  
> doesn't
> actually allocate the space anywhere.  (Unless you have it in a  
> different
> .cc file.)
>
> Add this to your source file:
>
> template <typename Type>
> Type* Singleton<Type>::ptr;

That worked. Thank you.

Now, why did I have to do that? The static functions that I wrote  
inside the class definition were allocated without issue. The code you  
had me add just looks like defining a function outside of a class  
header except in this case nothing new was added. Is there something I  
could have added to the class header that would have avoided that  
piece of code you gave me? If I had a non-template class with a static  
data member, gcc doesn't complain if I don't redefine it outside of  
the header. In other words, why does a template require the code you  
gave me and why doesn't a regular class then require something like  
the following:

class A
{
public:
   static int number;
};

int A::number;

I hope I'm conveying the question clearly. I'm trying to gain a better  
understanding to avoid future problems and it will help me remember  
all of this if I know why I'm doing it.

Thanks again,

R.



More information about the Gcc-help mailing list