标签:style blog http io ar color 使用 sp on
请读者先看这篇文章,【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}, };
class DeleteLong { public: void operator()(void *p) { delete static_cast<long*>(p); } }; class DeleteString { public: void operator()(void *p) { delete static_cast<string*>(p); } }; class DeleteDouble { public: void operator()(void *p) { delete static_cast<double*>(p); } }; class ExportData { union { string * sp; long* lp; double* dp; void* vp; }; enum my_type {SP,LP,DP} types;//change it to object. static unordered_map<type_index,my_type> typeMap; static vector<function<void(void*)>> deleters; 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); (deleters[types])(vp); 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)); }
//这里可以改成重载,void getData(long& t){...} void getData(sting& t){....} void getData(double& t){...}调用其他类型则编译错误 }; 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}, }; vector<function<void(void*)>> ExportData::deleters {DeleteString(),DeleteLong(),DeleteDouble(),};
这里是测试代码:
int main() { long i=5; long j=0; string s="Hello"; string ss; ExportData p(i); p.setData(++i); p.getData(j); p.setData(s); p.getData(ss); cout<<j<<endl; cout<<ss<<endl; return 0; }
【C++模版之旅】项目中一次活用C++模板(traits)的经历 -新注解
标签:style blog http io ar color 使用 sp on
原文地址:http://www.cnblogs.com/tangzhenqiang/p/4125626.html