Сравните две реализации Season_io (параграф D.3.2 и параграф D.4.7.1).
У меня не получилось запустить пример.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
#include <iostream> using std::cout; using std::endl; #include <locale> using std::locale; using std::messages; using std::use_facet; #include <string> using std::string; enum Season {spring, summer, fall, winter}; class Season_io:public locale::facet { const messages<char>& m;//директория сообщений int cat;//каталог сообщений public: class Missing_messages{}; Season_io(int i=0):locale::facet(i), m(use_facet<Season_messages>(locale())), cat(m.open(message_directory,locale())) { if(cat>0)throw Missing_messages(); } ~Season_io(){}//что бы можно было уничтожать объекты Season_io(параграф D.3) const string& to_str(Season x)const;//строковое представление х bool from_str(const string& s,Season& x)const;//поместить Season соответствий s в х static locale::id id; //объект идентификации фасета. }; locale::id Season_io::id;//определяем идентифицирующий объект const string& Season_io::to_str(Season x)const { return m->get(cat,x,"no-such-season"); } bool Season_io::from_str(const string& s, Season& x)const { for(int i=Season::spring;i<Season::winter;i++) if(m->get(cat,i,"no-such-season")==s) { x=Season(i); return true; } return false; } int main() { return 0; } |
Там какой то каталог сообщений используется, хз. пытался я каталог разобрать, но не получилось. Попробовал в этих сообщениях разобраться снова не вышло, да я не долго разбирался вот код:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
#include <iostream> using std::cout; using std::endl; using std::cerr; #include <fstream> using std::ifstream; #include <locale> using std::locale; using std::messages; using std::use_facet; using std::has_facet; #include <string> using std::string; #include <vector> using std::vector; #include <cstdlib> using std::exit; struct Set { vector<string> msgs; }; struct Cat { vector<Set> sets; }; class My_messages:public messages<char> { vector<Cat>& catalogs; public: explicit My_messages(size_t=0):catalogs(*new vector<Cat>){} catalog do_open(const string& s,const locale& loc)const;//открыть каталог s string do_get(catalog c,int s,int m,const string&)const;//взять сообщ-е (s,m) из с void do_close(catalog cat)const { if(catalogs.size()<=cat)catalogs.erase(catalogs.begin()+cat); } ~My_messages(){delete &catalogs;} }; string My_messages::do_get(catalog cat, int set, int msg, const string& def)const { if(catalogs.size()<=cat)return def; Cat& c=catalogs[cat]; if(c.sets.size()<=set)return def; Set& s=c.sets[set]; if(s.msgs.size()<=msg)return def; return s.msgs[msg]; } messages<char>::catalog My_messages::do_open(const string& n, const locale& loc)const { cout <<"Mu tyt"<<endl; exit(1); string nn=n+locale().name(); ifstream f(nn.c_str()); if(!f)return -1; catalogs.push_back(Cat()); Cat& c=catalogs.back(); string s; while(f>>s&&s=="<<<")//читаем Set { c.sets.push_back(Set()); Set& ss=c.sets.back(); while(getline(f,s)&&s!=">>>")ss.msgs.push_back(s);//читаем сообщение } return catalogs.size()-1; } int main() { if(!has_facet<My_messages>(locale())) { cerr <<"no messages facet found in "<<locale().name()<<'\n'; exit(1); } const messages<char>& m=use_facet<My_messages>(locale()); string message_directory; message_directory="file.txt"; int cat=m.open(message_directory,locale()); if(cat<0) { cerr <<"no catalog found\n"; exit(1); } cout <<m.get(cat,0,0,"Missed agein!")<<endl; cout <<m.get(cat,1,2,"Missed agein!")<<endl; cout <<m.get(cat,1,3,"Missed agein!")<<endl; cout <<m.get(cat,3,0,"Missed agein!")<<endl; return 0; } |
Ну ладно примерно смысл мы поняли, щас код самый первый скинем.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
#include <iostream> using std::cout; using std::cin; using std::endl; using std::ostream; using std::istream; using std::ios_base; #include <locale> using std::locale; using std::has_facet; using std::use_facet; #include <string> using std::string; #include <algorithm> using std::find; enum Season {spring, summer, fall, winter}; class Season_io : public locale::facet { public: Season_io(int i=0):locale::facet(i){} ~Season_io(){}//обеспечивает возможность уничтожения объектов Season_io virtual const string& to_str(Season x)const =0;//строковое представление для x //place Season corresponding to s in x virtual bool from_str(const string& s, Season& x)const =0; static locale::id id;//объект идентификации фасета }; locale::id Season_io::id;//определяем идентифицирующий объект ostream& operator<<(ostream& s, Season x) { const locale& loc=s.getloc();//извлекаем stream's locale if(has_facet<Season_io>(loc)) return s <<use_facet<Season_io>(loc).to_str(x); return s <<int(x); } istream& operator>>(istream& s, Season& x) { const locale& loc=s.getloc();//извлекаем stream's locale if(has_facet<Season_io>(loc))//читаем алфавитное представление { const Season_io& f=use_facet<Season_io>(loc); string buf; if(!(s>>buf&&f.from_str(buf,x)))s.setstate(ios_base::failbit); return s; } int i;//читаем числовое представление s >>i; x=Season(i); return s; } class US_season_io:public Season_io { static const string seasons[]; public: const string& to_str(Season) const; bool from_str(const string&, Season&)const; //обратите внимание отсутствие US_season_io::id }; const string US_season_io::seasons[]={"spring","summer","fall","winter"}; const string& US_season_io::to_str(Season x) const { if(x<spring||winter<x) { static const string ss="no-such-season"; return ss; } return seasons[x]; } bool US_season_io::from_str(const string& s, Season& x) const { const string* beg=&seasons[spring]; const string* end=&seasons[winter]+1; const string* p=find(beg,end,s); if(p==end)return false; x=Season(p-beg); return true; } int main() { Season x; //Используем локализацию по умолчанию (нет фасета Season_io)-ввод вывод целых cin >>x; cout <<x<<endl; locale loc(locale(),new US_season_io); cout.imbue(loc);//используем локализацию с фасетом Season_io cin.imbue(loc);//используем локализацию с фасетом Season_io cin >>x; cout <<x<<endl; return 0; } |
Ну и что сравнивать, там просто используются сообщения из какого то каталога, вообщем не охота мне на это тратить время, тем более оно наврятли мне пригодится, когда понадобиться тогда и разберем эту тему.
[youtube]https://www.youtube.com/watch?v=F7-HokHNTwA[/youtube]