Reference

TEMPLATES

// 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> //...

TEMPLATES & DESIGN PATTERN

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 ?

MORE

designpatterns.txt · Last modified: 2022/04/16 12:22 (external edit)
 
Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki