请读者先看这篇文章,【C++模版之旅】项目中一次活用C++模板(traits)的经历。 对于此篇文章提出的问题,我给出一个新的思路。
talking is cheap,show me the code.文章名字很大,仅仅是为了引起你的注意。
class ExportData
{
union
{
string * sp;
long* lp;
double* dp;
void* vp;
};
enum my_type {SP,LP,DP} types;
static unordered_map<type_index,my_type> typeMap;
public:
template <typename T> ExportData(T t)
{
if(typeMap.find(typeid(t))==typeMap.end())
assert(false);
vp=new T(t);
types= typeMap[typeid(T)];
}
template <typename T> void setData(T t)
{
if(typeMap.find(typeid(t))==typeMap.end())
assert(false);
switch(types)
{
case SP:
delete sp;
break;
case DP:
delete dp;
break;
case LP:
delete lp;
break;
}
vp=new T(t);
types=typeMap[typeid(T)];
}
template <typename T> void getData(T& t)
{
if(typeMap[typeid(T)]!=types) assert(false);
t=*(static_cast<T*>(vp));
}
};
unordered_map<type_index,ExportData::my_type> ExportData::typeMap
{
{typeid(string),ExportData::my_type::SP},
{typeid(long),ExportData::my_type::LP},
{typeid(double),ExportData::my_type::DP},
};
原文地址:http://blog.csdn.net/zjq2008wd/article/details/41517367