c++ 模板学习笔记2

一个可以保存任意参数类型的字典类。 

#include <stdio.h>
#include <assert.h>
#include <iostream>
#include <string>
#include <vector>
#include <map>

using namespace std;

struct BaseDictValue
{	
	virtual ~BaseDictValue(){};
};

template <class T>
struct DictValue: public BaseDictValue
{
	DictValue():myType(&VType){}
	
	T value;
	char * myType;
	static char VType;
};
template <class T>
char DictValue<T>::VType = 0;


class Dict
{
public:
	template <class T>
	void set(string key, T value)
	{
		DictValue<T>* v = new DictValue<T>();
		v->value = value;
		
		if (dd[&DictValue<T>::VType].find(key) != dd[&DictValue<T>::VType].end())
		{
			delete dd[&DictValue<T>::VType][key];
		}
		
		dd[&DictValue<T>::VType][key] = v;
	}

	template <class T>
	T get(string key)
	{
		DictValue<T>* v = static_cast< DictValue<T>* >(dd[&DictValue<T>::VType][key]);
		return v->value;
	}
	
	~Dict()
	{
		for (map< char*, map<string, BaseDictValue*> >::iterator i = dd.begin(); i != dd.end(); i++)
		{
			for (map<string, BaseDictValue*>::iterator j = i->second.begin(); j != i->second.end(); j++)
			{
				delete j->second;
			}
		}
	}
private:
	map< char*, map<string, BaseDictValue*> > dd;
}; 


int main()
{
	Dict aa;
	
	string value = "dddd";
	aa.set<string>("name", value);
	aa.set<string>("name", "fff");
	aa.set<int>("name", 666);
	
	string v = aa.get<string>("name");
	
	cout<<"string value="<<v<<"; int value="<<aa.get<int>("name")<<std::endl;

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值