0

I was coding a class template to implement a Singleton when an issue occured.

While having a static pointer in a .h file, it wouldnt compile because of a linker issue (lnk 2001 and lnk 1120 on vs 15).

I Simplified my code to have the more understandable issue :

#pragma once
#include "SingletonTemplate.h"
int main()
{
    SingletonTemplate<int>::test();
}

my class SingletonTemplate.h (there is no .cpp btw)

template<class T>class SingletonTemplate
{
public:
    static int myInt; 
    static void test()
    {
        SingletonTemplate<T>::myInt = 1;
    }
}

I read on several posts that the further declaration of the static variable can solve this issue. I added this outside of my function (but still in the .h) :

template< typename T >
int SingletonTemplate<T>::myInt;

Doing that solved my issue but I have no clue why. So, if someone could explain me what is the purpose of this line, it would be awesome.

Thanks in advance

Arkhain
  • 21
  • 1
  • 8
  • Something that helps me to reason about statics is to not picture them as belonging to the thing you declare them in. A static variable in a class is really just a global variable but its name is scoped to the class name. If you look at it that way it makes sense you need to define it somewhere in the global space. – NathanOliver Mar 13 '17 at 16:40
  • I already read that thread and didnt got the "one definition" thing. The thing that makes me confuse is : I want the static member to be "linked" to the type of class passed as template (since it's for a singleton implementation). – Arkhain Mar 13 '17 at 16:41
  • NathanOliver, ok, but why dont the compiler instantiate the variable each time the class template is instantiated with a diffetent template class? (not sure how to explin) – Arkhain Mar 13 '17 at 16:45
  • @Arkhain It does. `SingletonTemplate::myInt` is a different `int` from `SingletonTemplate::myInt`. – NathanOliver Mar 13 '17 at 16:47

0 Answers0