A
Alfonso Morra
Hi,
I've written a very simple Simpleton design pattern class template. This
was supposed to illustrate a point. Although it compiles without nay
errors, I get link errors (unresolved external), during linking - before
anyone jumps to conclusions that this is OT, please check the linker
error message below, it is NOT OT.
Here are my class declarations/definitions:
template <class T>
class Singleton {
public:
static T& instance();
protected:
Singleton() {}
private:
static T* instance_ ;
Singleton(const Singleton&) {}
void operator=(const Singleton&) {}
};
template <class T>
T& Singleton<T>::instance() {
if (!instance_)
instance_ = new T ;
return *instance_;
}
//Simple Test harness
class Test : public Singleton<Test> {
friend class Singleton<Test> ;
public:
int foo(void){ return 1 ; }
void bar(void) { ; }
virtual ~Test() { cout << "Dtor called" << endl ; }
private:
Test() { cout << "Ctor called" << endl ; }
};
The code to test this is below (header stuff not included for brevity)
int main() {
Foo &f = Foo::instance() ;
}
Here is the linker eror I get:
singleton error LNK2001: unresolved external symbol "private: static
class Test * Singleton<class Test>::instance_"
Can anyone spot where I'm going wrong?
I've written a very simple Simpleton design pattern class template. This
was supposed to illustrate a point. Although it compiles without nay
errors, I get link errors (unresolved external), during linking - before
anyone jumps to conclusions that this is OT, please check the linker
error message below, it is NOT OT.
Here are my class declarations/definitions:
template <class T>
class Singleton {
public:
static T& instance();
protected:
Singleton() {}
private:
static T* instance_ ;
Singleton(const Singleton&) {}
void operator=(const Singleton&) {}
};
template <class T>
T& Singleton<T>::instance() {
if (!instance_)
instance_ = new T ;
return *instance_;
}
//Simple Test harness
class Test : public Singleton<Test> {
friend class Singleton<Test> ;
public:
int foo(void){ return 1 ; }
void bar(void) { ; }
virtual ~Test() { cout << "Dtor called" << endl ; }
private:
Test() { cout << "Ctor called" << endl ; }
};
The code to test this is below (header stuff not included for brevity)
int main() {
Foo &f = Foo::instance() ;
}
Here is the linker eror I get:
singleton error LNK2001: unresolved external symbol "private: static
class Test * Singleton<class Test>::instance_"
Can anyone spot where I'm going wrong?