Created
January 29, 2015 00:01
-
-
Save jmlvanre/284db28c806c46a19c31 to your computer and use it in GitHub Desktop.
Templatized storage without forward declaration of types
This file contains 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 <unordered_set> | |
/* Templatized storage without forward declaration of types. */ | |
class TC { | |
public: | |
template<typename T> | |
class TM { | |
public: | |
virtual ~TM() { C->Part(this); } | |
protected: | |
TM() : C(GetTC()) { C->Join(this); } | |
private: | |
TC* C; | |
}; | |
/* Force singleton as the templatized storage is static */ | |
static TC* GetTC() { | |
static TC tc; | |
return &tc; | |
} | |
private: | |
TC() {} | |
template <typename T> | |
std::unordered_set<TM<T>*>& GetSet() { | |
static std::unordered_set<TM<T>*> set; | |
return set; | |
} | |
template <typename T> | |
void Join(TM<T>* tm) { | |
GetSet<T>().emplace(tm); | |
printf("Membership count = [%ld]\n", GetSet<T>().size()); | |
} | |
template <typename T> | |
void Part(TM<T>* tm) { | |
GetSet<T>().erase(tm); | |
printf("Membership count = [%ld]\n", GetSet<T>().size()); | |
} | |
}; | |
int main() { | |
class TMA : public TC::TM<int32_t> { | |
public: | |
TMA() {} | |
virtual ~TMA() {} | |
}; | |
class TMB : public TC::TM<int64_t> { | |
public: | |
TMB() {} | |
virtual ~TMB() {} | |
}; | |
TMA a1; | |
TMB b1; | |
TMA a2; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment