Skip to main content
gamedev.net
🔒 Locked

Singleton - unresolved external?

Started by bilsa 4 replies 500+ views
Original Post
bilsa
bilsa
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]
Jingo
Jingo
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;
bilsa
bilsa
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!
PlayGGY
PlayGGY
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.
And the rockets' red glare, the bombs bursting in air,gave proof through the fight that our flag was still there.Oh say, does that star-spangled banner yet waveover the land of the free and the home of the brave?
UltimaX
UltimaX
typedef Singleton; MyClass; ??????
typedef Singleton MyClass;

-UltimaX-

"You wished for a white christmas... Now go shovel your wishes!"
bilsa
bilsa
yes... some spelling mistakes, I got it working fine now... thx anyway

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.