Topic: Why does ostream_iterator require a type parameter for the object being written to the stream?


Author: drpizza@anti-flash.co.uk ("DrPizza")
Date: Thu, 11 Sep 2003 16:36:12 +0000 (UTC)
Raw View
It seems to me that this requires needless duplication:

std::vector<int> v; // I specify the type stored within the vector here
std::generate_n(std::back_inserter(v), 16, &std::rand);
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, "\n")); //
and I have to specify it here, too

Is there some reason why ostream_iterator isn't something such as:
template<typename Elem = char, typename Traits = std::char_traits<Elem> >
struct generic_ostream_iterator : public
std::iterator<std::output_iterator_tag, void, void, void, void>
{
 typedef std::basic_ostream<Elem, Traits> ostream_type;
 generic_ostream_iterator(ostream_type& os_) : os(&os_), delim(0) {}
 generic_ostream_iterator(ostream_type& os_, const Elem* delim_) : os(&os_),
delim(delim_) {}
 template <typename T>
 generic_ostream_iterator<Elem, Traits>& operator=(const T& value)
 {
  *os << value;
  if(0 != delim) { *os << delim; }
  return *this;
 }
 generic_ostream_iterator<Elem, Traits>& operator*() { return *this; }
 generic_ostream_iterator<Elem, Traits>& operator++() { return *this; }
 generic_ostream_iterator<Elem, Traits> operator++(int) { return *this; }
protected:
 const Elem* delim;
 ostream_type* os;
};

This would allow usage such as:
std::vector<int> v;
std::generate_n(std::back_inserter(v), 16, &std::rand);
std::copy(v.begin(), v.end(), generic_ostream_iterator<>(std::cout, "\n")); //
no longer do I have to specify what the vector stores -- it gets figured out
automagically

Is there any rationale why the type is made a class template parameter
(thereby preventing inference) when it appears (to me, at least) that it could
just as well have been a function template parameter (and so determined
automagically)?


--
Now Playing:  Sasha Riker - Spontaneity 13 (06-03-2002) (D I G I T A L L Y - I
M P O R T E D - European Trance, Techno, Hi-NRG... we can't define it!)



---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]