//通过结构体/类的类型来作为模板参数的tag, //用来区分tag之间的区别。 //made by davidsu33 //例如对于某个全局的静态变量,你如果希望有 //很多份,但是其实现又是一样的,你可以考虑 //以模板的形式,通过类tag来区分 //而且还可以根据实际需要来特化模板 #include "stdafx.h" #include <iostream> #include <cassert> using namespace std; template<class Tag> class Instance; template<class Tag> class Instance { public: ~Instance(){}; static Instance &getInstance() { static Instance s_instance; return s_instance; } void doOne() { cout<<"do One"<<endl; } void doTwo() { cout<<"do Two"<<endl; } private: Instance(){}; Instance& operator=(const Instance&); Instance(const Instance&); }; struct TagOne{}; struct TagTwo{}; struct TagThree{}; typedef Instance<TagOne> InstanceOne; typedef Instance<TagTwo> InstanceTwo; template<> class Instance<TagThree> { public: void doOne() { cout<<"do Three"<<endl; } void doTwo() { cout<<"do Three"<<endl; } }; void test_instance() { InstanceOne &one = InstanceOne::getInstance(); InstanceTwo &two = InstanceTwo::getInstance(); void* ptrOne = static_cast<void*>(&one); void *ptrTwo = static_cast<void*>(&two); assert(ptrOne != ptrTwo); Instance<TagThree> three1, three2, three; three.doOne(); three.doTwo(); } int _tmain(int argc, _TCHAR* argv[]) { test_instance(); getchar(); return 0; }
时间: 2024-10-25 19:16:19