Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Created December 4, 2013 14:17
Show Gist options
  • Save dgodfrey206/7788108 to your computer and use it in GitHub Desktop.
Save dgodfrey206/7788108 to your computer and use it in GitHub Desktop.
Inserter for a Car object.
#include <iostream>
#include <string>
#include <typeinfo>
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>&, Car const&);
};
template<class charT, class iter = ostreambuf_iterator<charT> >
class car_put
: public locale::facet
{
public:
typedef charT char_type;
typedef iter iter_type;
static locale::id id;
public:
car_put(int refs = 0)
: locale::facet(refs)
{ }
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) = ' ';
f.put(it, str, str.fill(), static_cast<unsigned long>(year));
}
};
template<class charT, class iter>
locale::id car_put<charT, iter>::id;
template<class charT>
basic_ostream<charT>& operator<<(basic_ostream<charT>& os, Car const& c)
{
locale loc = os.getloc();
try
{
auto& f = use_facet<car_put<charT> >(loc);
f.put(os, os, c.name, c.year);
} catch (const bad_cast&) { }
return os;
}
template<class C>
class car_printer
{
public:
car_printer(C const& c)
: c(c)
{ }
private:
Car c;
template<class charT, class Facet = car_put<charT> >
void print(basic_ostream<charT>& os, const C& c, Facet* f = new Facet) const
{
locale original = os.getloc();
if (!has_facet<Facet>(original))
os.imbue(locale(original, f));
os << c << endl;
os.imbue(original);
}
template<class charT>
friend basic_ostream<charT>& operator<<(basic_ostream<charT>& os, const car_printer<C>& cp)
{
cp.print(os, cp.c);
return os;
}
};
template<class C>
car_printer<C> put_car(C const& c)
{
return car_printer<C>(c);
}
int main()
{
Car c("Honda", 2014);
cout << put_car(c);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment