要實現的效果:
//main.cpp :: main()map<char, vector<bool> > temp= make_test_val();cout<< toString(temp);
用模板實現toString(任意類型) 然後就方便了
以下是代碼:
//tools.h#include<map>#include<vector>using namespace std;//---toString---//builderclass tostring_bulider{public: string _str; string _prefix; string _comma; string _suffix; bool first_item; tostring_bulider(){ first_item= true; _prefix= "["; _suffix= "]"; _comma= ", "; } void prefix(){ _str+= _prefix; } template<typename T> void push(const T& item){ if(first_item){ first_item= false; }else{ _str+= _comma; } _str+= ::toString(item); } void suffix(){ _str+= _suffix; } string toString()const{return _str;}};class tostring_map_bulider{public: string _str; string _prefix; string _comma; string _eq; string _suffix; bool first_item; tostring_map_bulider(){ first_item= true; _prefix= "{"; _suffix= "}"; _comma= ", "; _eq= ":"; } void prefix(){ _str+= _prefix; } template<typename T> void push(const T& item){ if(first_item){ first_item= false; }else{ _str+= _comma; } _str+= ::toString(item.first)+ _eq+ ::toString(item.second); } void suffix(){ _str+= _suffix; } string toString()const{return _str;}};//etc.//default typestring toString(const string& s){return s;}//system typetemplate<typename T>string toString(const T& v){ return v.toString();}template<>string toString<char>(const char& v){ return string()+v;}template<>string toString<bool>(const bool& v){ return v? "true": "false";}//etc.//Containertemplate<typename T, typename Tfmt>string toString(const T& v, Tfmt fmter){ fmter.prefix(); for(auto iter = begin(v); iter!=end(v); ++iter) fmter.push(*iter); fmter.suffix(); return move(toString(fmter));}//std Containertemplate<typename T>string toString(const vector<T>& v){ return toString(v,tostring_bulider());}template<typename Tk, typename Tv>string toString(const map<Tk,Tv>& v){ return toString(v, tostring_map_bulider());}//etc.
但是這樣顯示出來是這樣的:
{a:[false, false, true, false], b:[false, false, true, false, true, false, true, false]}
可以添加以下代碼:
//main.cppclass my_tostring_map_bulider: public tostring_map_bulider{public:string toString_vector_bool(const vector<bool>& v){string ret;for(auto iter= begin(v); iter!=end(v); ++iter)ret+= *iter? "1": "0";return ret;}void push(const pair<char, vector<bool> >& item){if(first_item){first_item= false;}else{_str+= _comma;}_str+= ::toString(item.first)+ _eq+ toString_vector_bool(item.second);}};
然後這樣用:
//main.cpp :: main()map<char, vector<bool> > temp= make_test_val();cout<< toString(temp, my_tostring_map_bulider());
輸出是這樣的:
{a:0010, b:00101010}