problem compiling singleton template class

J

Jim Strathmeyer

So I'm trying to implement a singleton template class, but I'm getting a
confusing 'undefined reference' when it tries to link. Here's the code
and g++'s output. Any help?

// singleton.h

template <class T>
class Singleton : public T {
public:
static T * Instance();

protected:
Singleton();
~Singleton();

private:
static Singleton<T> * instance;
};

// singleton.cpp

#include <iostream>
#include "singleton.h"

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

template <class T> T * Singleton<T>::Instance() {
return (instance?instance:(instance = new Singleton<T>));
}

template <class T> Singleton<T>::Singleton() {
std::cout << "constructing singleton" << std::endl;
}

template <class T> Singleton<T>::~Singleton() {
std::cout << "destructing singleton" << std::endl;
}

// a.h

class A {
protected:
A();
virtual ~A();
};

// a.cpp

#include "a.h"
#include <iostream>

A::A() {
std::cout << "constructing A" << std::endl;
}

A::~A() {
std::cout << "destructing A" << std::endl;
}

// main.cpp

#include "a.h"
#include "singleton.h"
#include <iostream>

int main(int argc, char ** argv) {
A * a = Singleton<A>::Instance();
return 0;
}

g++ -g -Wall -MD a.o main.o singleton.o -o a.out
main.o(.text+0x1f): In function `main':
main.cpp:8: undefined reference to `Singleton<A>::Instance()'
collect2: ld returned 1 exit status
make: *** [singleton] Error 1
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,967
Messages
2,570,148
Members
46,694
Latest member
LetaCadwal

Latest Threads

Top