一个可以保存任意参数类型的字典类。
#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;
}