Skip to content

Instantly share code, notes, and snippets.

@glass5er
Last active November 14, 2018 11:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glass5er/5813190 to your computer and use it in GitHub Desktop.
Save glass5er/5813190 to your computer and use it in GitHub Desktop.
When you create a subclass of singleton, use template.
#include <iostream>
#include <string>
using namespace std;
//----------------
template <class U>
class SingletonParent
{
public:
static U* getInstance() {
static U instance;
return &instance;
}
protected:
//-- template func in template class available
template<typename T> void print2Times(T v);
SingletonParent() {
base_str = string("BASE");
}
virtual ~SingletonParent() {}
string base_str;
};
//-- use template succession
class SingletonChild : public SingletonParent<SingletonChild> {
public:
SingletonChild() {
child_value = 0;
}
~SingletonChild() {}
void set(int v) { child_value = v; }
int get() { return child_value; }
void print() {
print2Times(base_str);
print2Times(child_value);
}
private:
int child_value;
};
//-- when defining template func in template class,
//-- 2 template declaraton required
template<class U> template<typename T>
void
SingletonParent<U>::print2Times(T v)
{
cout << v << v << endl;
}
//----------------
int
main(int argc, char const* argv[])
{
//-- actually the same instance
SingletonChild *inst1 = SingletonChild::getInstance();
SingletonChild *inst2 = SingletonChild::getInstance();
//-- both 0
cout << inst1->get() << endl;
cout << inst2->get() << endl;
//-- BASEBASE, 00
inst1->print();
inst2->set(3);
//-- both 3
cout << inst1->get() << endl;
cout << inst2->get() << endl;
//-- BASEBASE, 33
inst1->print();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment