Last active
December 30, 2015 01:09
-
-
Save dgodfrey206/7754537 to your computer and use it in GitHub Desktop.
Writing output for a Car class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
using namespace std; | |
class Car | |
{ | |
public: | |
Car(const basic_string<char>& _name, int _year) | |
: name(_name), year(_year) | |
{ } | |
private: | |
basic_string<char> name; | |
int year; | |
template<class charT> | |
friend basic_ostream<charT>& operator<<(basic_ostream<charT>&, const Car&); | |
}; | |
template<class charT, class iter = ostreambuf_iterator<charT>> | |
class car_put | |
: public locale::facet | |
{ | |
public: | |
typedef charT char_type; | |
typedef iter iter_type; | |
public: | |
explicit car_put(int refs = 0) | |
: locale::facet(refs) | |
{ } | |
static locale::id id; | |
virtual void put(iter_type it, basic_ios<charT>& str, | |
const basic_string<charT>& name, | |
int year) const | |
{ | |
do_put(it, str, name, year); | |
} | |
protected: | |
virtual void do_put(iter_type it, basic_ios<charT>& str, | |
const basic_string<charT>& name, | |
int year) const | |
{ | |
auto& f = use_facet<num_put<charT>>(str.getloc()); | |
copy(name.begin(), name.end(), it); | |
*it = ' '; | |
f.put(it, str, str.fill(), static_cast<unsigned long>(year)); | |
} | |
virtual ~car_put() = default; | |
}; | |
template<class charT, class iter> | |
locale::id car_put<charT, iter>::id; | |
template<class charT> | |
basic_ostream<charT>& operator<<(basic_ostream<charT>& os, const Car& c) | |
{ | |
typename basic_ostream<charT>::sentry ok(os); | |
if (ok) | |
{ | |
locale loc = os.getloc(); | |
try | |
{ | |
auto& f = use_facet<car_put<charT>>(loc); | |
f.put(os, os, c.name, c.year); | |
} catch(...) { } | |
} else | |
{ | |
os.setstate(ios_base::failbit); | |
} | |
return os; | |
} | |
template<class charT, class Facet = car_put<char>> | |
void print_car(basic_ostream<charT>& os, const Car& c, Facet* f = new Facet{}) | |
{ | |
locale original = os.getloc(); | |
os.imbue(locale(original, f)); | |
os << c << endl; | |
os.imbue(original); | |
} | |
int main() | |
{ | |
Car a{"Ford", 2012}, b{"Lexus", 2014}; | |
print_car(cout, a); | |
print_car(cout, b); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment