模板参数tag的用法

//通过结构体/类的类型来作为模板参数的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;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值