   Singleton class problem[C++]
  I am currently trying to write a singleton class to inherit from, but I get weird error messages when I Inherit from it.Log.h#ifndef LOG_H_#define LOG_H_#include "Singleton.h"#include <fstream>#define LOG_APP 1#define LOG_CLIENT 2#define LOG_SERVER 4class Log : public Singleton<Log>{protected:std::ofstream app;std::ofstream client;std::ofstream server;public:Log();virtual ~Log();void Write(int target, const char *msg, ...);};#endif /* LOG_H_ */Log.cpp#include "Log.h"#include "Singleton.h"#include <cstdarg>#include <iostream>using namespace std;Log::Log() //ERROR 1{app.open("applog.txt");client.open("clntlog.txt");server.open("srvrlog.txt");} //ERROR 2Log::~Log(){app.close();client.close();server.close();} //ERROR 3void Log::Write(int target, const char *msg, ...){va_list args;va_start(args,msg);char szBuf[1024];vsprintf(szBuf,msg,args);if (target & LOG_APP){app << szBuf << endl;app.flush();}if (target & LOG_CLIENT){client << szBuf << endl;client.flush();}if (target & LOG_SERVER){server << szBuf << endl;server.flush();}}Singleton.h#ifndef SINGLETON_H_#define SINGLETON_H_#include <stdlib.h>template<typename T>class Singleton{private:static T* p;public:Singleton();~Singleton();static T& GetSingleton();static T* GetSingletonPtr();};template <typename T> T* Singleton <T>::p = 0;#endif /* SINGLETON_H_ */Singleton.cpp#include "Singleton.h"template<class T>Singleton<T>::Singleton(){if(p);{exit(1);}//use a cunning trick to get the singleton pointing to the start of//the whole, rather than the start of the Singleton part of the objectint offset = (int)(T*)1 - (int)(Singleton <T>*)(T*)1;p = (T*)((int)this + offset);}template<class T>Singleton<T>::~Singleton(){if(!p){exit(1);}p=0;}template<class T>T& Singleton<T>::GetSingleton(){if(!p){exit(1);}return *p;}template<class T>T* Singleton<T>::GetSingletonPtr(){if(!p){exit(1);}return p;}ERROR 1:undefined reference to `Singleton<Log>::Singleton()'ERROR 2:undefined reference to `Singleton<Log>::~Singleton()'ERROR 3:undefined reference to `Singleton<Log>::~Singleton()'does anyone know what's causing these errors, and how to fix them?   
  You'll find your answer here.   ;  Quick answer: you've got to define methods of template classes in the same header file in which the template is declared. Basically, just move all the definitions in Singleton.cpp to Singleton.h.   ;  ^^Your question's been answered, but I'd recommend changing this pointer hack:int offset = (int)(T*)1 - (int)(Singleton <T>*)(T*)1;p = (T*)((int)this + offset);to:p = static_cast<T*>(this);Which achieves the same thing, but leaves the offset details up to the compiler to get right.   