// file:///~/singleton.hpp template <class T> class Singleton { public: static T* get() { if ( instance == 0 ) instance = new T; return instance; } protected: Singleton() { } ~Singleton() { } private: static T* instance; };
template<class T> T* Singleton<T>::instance = NULL; // here the tricky part
// file:///~/main.cpp #include <string> using namespace std; #include "singleton.hpp"
int main() { Singleton<string>::get(); return EXIT_SUCCESS; }
Note: Microsoft msvs allows default types , not GCC so avoid those :
template<class T = char> //...
what do u think of this weird code :
/// Design Pattern (with templates) template <class T> class VisitorAble { public: virtual int visit(T & in_data)=0; };
template <class T> class AcceptAble { public: virtual int accept(T & in_visitor) { in_visitor.visit( *this ); } };
class Visitor : public Visitor<Data> { public: ... visit ... };
class Data : public AcceptAble<VisitorAble<Data> > {};
// recursive template ?