• ### Announcements

#### Archived

This topic is now archived and is closed to further replies.

# Singleton - unresolved external?

## Recommended Posts

hmm, to me it seems like I have done an ok Singleton class, but It seems I get an external error when I build the application :/ Singleton.h
#ifndef SINGLETON
#define SINGLETON

template <class T>;
class Singleton {
public:
static T& GetInstance();
private:
Singleton();
~Singleton();
Singleton(const Singleton&);
Singleton& operator = (const Singleton&);

static T& m_instance;
};

template <class T>
T* Singleton<T>::m_instance = 0;

#endif

Singleton.cpp
#include "Singleton.h"

template <class T>
T& Singleton<T>::GetInstance() {
if (m_instance == 0) {
m_instance = new T;
}
return *m_instance;
}


then I have a class MyClass and try to make it a singleton, like this:
typedef Singleton<MyClass>; MyClass;
MyClass& g_MyClass = MyClass::GetInstance();

But the "MyClass& g_MyClass = MyClass::GetInstance();" gives me an unresolved external when linking, and I can't figure out what is wrong :/ Would appreicate some help on this [edited by - bilsa on January 5, 2004 2:09:00 PM]

##### Share on other sites
Its the old class template function definition in a seperate .cpp file problem.

Theres 3 solutions i know of,

1) Define GetInstance inside the the header file.
2) #include the .cpp file at the bottom of the header file
3) Use the export keyword (which isnt very well supported by compilers)

Another problem seems to be m_instance, you are treating it as a pointer when you have declared it as static T& m_instance;

##### Share on other sites
hmm, now that I recall it this was the problem that I had once when I used VC++ 6.0

But then I got a hand on VC++ .NET 2003 and I was told that this compiler was enhanced in templates, and that you could have the templated functions in a .cpp without any problem what so ever. So I haven''t thought that it could be the problem... but now that you mention it :/

Does anyone know anything about VC++ .NET 2003 and how it supports templates?

thx!

##### Share on other sites
It wouldn''t make any sense to compile every possible version of a template class, even ones of types that the .cpp file doesn''t know exists, before linking stage. That is why templates have to be visible to the code that uses it.

##### Share on other sites
typedef Singleton; MyClass; ??????
typedef Singleton MyClass;

-UltimaX-

"You wished for a white christmas... Now go shovel your wishes!"

##### Share on other sites
yes... some spelling mistakes, I got it working fine now... thx anyway

• ## Partner Spotlight

• ### Forum Statistics

• Total Topics
627654
• Total Posts
2978442

• 10
• 12
• 22
• 13
• 33