c++ - Why does ostream_iterator need to explicitly declare the type of objects to output? -


in current c++, class ostream_iterator designed following:

// excerpted standard c++  template<class t, ...> class ostream_iterator { public:     ostream_iterator(ostream_type&);     ...      ostream_iterator<t,...>& operator =(const t&);     ... }; 

to me, design suboptimal. because user must specify type t when declaring ostream_iterator this: ostream_iterator<int> oi(cout); in fact, cout can take type of object argument, rather 1 type. obvious restriction.

// below own version  // doesn't need template parameter here class ostream_iterator { public:     ostream_iterator(ostream_type&);     ...      // define template member function can take type of argument , output     template<class t>      ostream_iterator<t,...>& operator =(const t&);     ... }; 

now, can use follows:

ostream_iterator oi(cout); 

i think more generic , more elegant

ostream_iterator<int> oi(cout); 

am right?

it appears right.

let's see if can construct ostream_iterator not need template argument.

the iterator works copying values it, *iter = x; ++iter; iterator cheats making operator* return , ++iter returning without changing state. "magic" in operator= performs output.

the "cout" must class member of type ostream*. needs pointer iterators must assignable, assign member (call os) address of stream passed in.

so overload operator= way:

template< typename t > our_ostream_iterator& operator=( const t& t ) {    (*os) << t;    if( delim )       (*os) << delim;    return *this; } 

note templatised operator= should not oveload operator=(our_ostream_iterator const&) more specialised template.

you still want template on element type call our_basic_ostream_iterator

ostream_iterator still remain template class on element type. thus:

template< typename e, typename tr=char_traits<e> > class our_basic_ostream_iterator : public std::iterator< /*traits here*/ > { public:    typedef e element_type;    typedef tr traits_type;    typedef basic_ostream< e, tr > stream_type; private:    stream_type * os;    e* delim; public:    our_basic_ostream_iterator( stream_type s, e* d = null ) :       os( &s ), delim( d )    {    }     our_basic_ostream_iterator& operator++() { return *this; }    our_basic_ostream_iterator operator++(int) { return *this; }    our_basic_ostream_iterator& operator*() { return *this; }     template< typename t >    our_basic_ostream_iterator& operator=( const t& t ); // above }; 

and of course

typedef our_basic_ostream_iterator<char> our_ostream_iterator; typedef our_basic_ostream_iterator<wchar_t> our_wostream_iterator; 

Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -