Last active
November 14, 2018 11:16
-
-
Save glass5er/5813190 to your computer and use it in GitHub Desktop.
When you create a subclass of singleton, use template.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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