ostream

Go to the documentation of this file.
00001 // Output streams -*- C++ -*-
00002 
00003 // Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
00004 // 2006, 2007, 2008, 2009, 2010, 2011
00005 // Free Software Foundation, Inc.
00006 //
00007 // This file is part of the GNU ISO C++ Library.  This library is free
00008 // software; you can redistribute it and/or modify it under the
00009 // terms of the GNU General Public License as published by the
00010 // Free Software Foundation; either version 3, or (at your option)
00011 // any later version.
00012 
00013 // This library is distributed in the hope that it will be useful,
00014 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00015 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00016 // GNU General Public License for more details.
00017 
00018 // Under Section 7 of GPL version 3, you are granted additional
00019 // permissions described in the GCC Runtime Library Exception, version
00020 // 3.1, as published by the Free Software Foundation.
00021 
00022 // You should have received a copy of the GNU General Public License and
00023 // a copy of the GCC Runtime Library Exception along with this program;
00024 // see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
00025 // <http://www.gnu.org/licenses/>.
00026 
00027 /** @file include/ostream
00028  *  This is a Standard C++ Library header.
00029  */
00030 
00031 //
00032 // ISO C++ 14882: 27.6.2  Output streams
00033 //
00034 
00035 #ifndef _GLIBCXX_OSTREAM
00036 #define _GLIBCXX_OSTREAM 1
00037 
00038 #pragma GCC system_header
00039 
00040 #include <ios>
00041 #include <bits/ostream_insert.h>
00042 
00043 namespace std _GLIBCXX_VISIBILITY(default)
00044 {
00045 _GLIBCXX_BEGIN_NAMESPACE_VERSION
00046 
00047   // [27.6.2.1] Template class basic_ostream
00048   /**
00049    *  @brief  Controlling output.
00050    *  @ingroup io
00051    *
00052    *  This is the base class for all output streams.  It provides text
00053    *  formatting of all builtin types, and communicates with any class
00054    *  derived from basic_streambuf to do the actual output.
00055   */
00056   template<typename _CharT, typename _Traits>
00057     class basic_ostream : virtual public basic_ios<_CharT, _Traits>
00058     {
00059     public:
00060       // Types (inherited from basic_ios (27.4.4)):
00061       typedef _CharT                            char_type;
00062       typedef typename _Traits::int_type        int_type;
00063       typedef typename _Traits::pos_type        pos_type;
00064       typedef typename _Traits::off_type        off_type;
00065       typedef _Traits                           traits_type;
00066       
00067       // Non-standard Types:
00068       typedef basic_streambuf<_CharT, _Traits>      __streambuf_type;
00069       typedef basic_ios<_CharT, _Traits>        __ios_type;
00070       typedef basic_ostream<_CharT, _Traits>        __ostream_type;
00071       typedef num_put<_CharT, ostreambuf_iterator<_CharT, _Traits> >        
00072                                 __num_put_type;
00073       typedef ctype<_CharT>                     __ctype_type;
00074 
00075       // [27.6.2.2] constructor/destructor
00076       /**
00077        *  @brief  Base constructor.
00078        *
00079        *  This ctor is almost never called by the user directly, rather from
00080        *  derived classes' initialization lists, which pass a pointer to
00081        *  their own stream buffer.
00082       */
00083       explicit 
00084       basic_ostream(__streambuf_type* __sb)
00085       { this->init(__sb); }
00086 
00087       /**
00088        *  @brief  Base destructor.
00089        *
00090        *  This does very little apart from providing a virtual base dtor.
00091       */
00092       virtual 
00093       ~basic_ostream() { }
00094 
00095       // [27.6.2.3] prefix/suffix
00096       class sentry;
00097       friend class sentry;
00098       
00099       // [27.6.2.5] formatted output
00100       // [27.6.2.5.3]  basic_ostream::operator<<
00101       //@{
00102       /**
00103        *  @brief  Interface for manipulators.
00104        *
00105        *  Manipulators such as @c std::endl and @c std::hex use these
00106        *  functions in constructs like "std::cout << std::endl".  For more
00107        *  information, see the iomanip header.
00108       */
00109       __ostream_type&
00110       operator<<(__ostream_type& (*__pf)(__ostream_type&))
00111       {
00112     // _GLIBCXX_RESOLVE_LIB_DEFECTS
00113     // DR 60. What is a formatted input function?
00114     // The inserters for manipulators are *not* formatted output functions.
00115     return __pf(*this);
00116       }
00117 
00118       __ostream_type&
00119       operator<<(__ios_type& (*__pf)(__ios_type&))
00120       {
00121     // _GLIBCXX_RESOLVE_LIB_DEFECTS
00122     // DR 60. What is a formatted input function?
00123     // The inserters for manipulators are *not* formatted output functions.
00124     __pf(*this);
00125     return *this;
00126       }
00127 
00128       __ostream_type&
00129       operator<<(ios_base& (*__pf) (ios_base&))
00130       {
00131     // _GLIBCXX_RESOLVE_LIB_DEFECTS
00132     // DR 60. What is a formatted input function?
00133     // The inserters for manipulators are *not* formatted output functions.
00134     __pf(*this);
00135     return *this;
00136       }
00137       //@}
00138 
00139       // [27.6.2.5.2] arithmetic inserters
00140       /**
00141        *  @name Arithmetic Inserters
00142        *
00143        *  All the @c operator<< functions (aka <em>formatted output
00144        *  functions</em>) have some common behavior.  Each starts by
00145        *  constructing a temporary object of type std::basic_ostream::sentry.
00146        *  This can have several effects, concluding with the setting of a
00147        *  status flag; see the sentry documentation for more.
00148        *
00149        *  If the sentry status is good, the function tries to generate
00150        *  whatever data is appropriate for the type of the argument.
00151        *
00152        *  If an exception is thrown during insertion, ios_base::badbit
00153        *  will be turned on in the stream's error state without causing an
00154        *  ios_base::failure to be thrown.  The original exception will then
00155        *  be rethrown.
00156       */
00157       //@{
00158       /**
00159        *  @brief  Basic arithmetic inserters
00160        *  @param  A variable of builtin type.
00161        *  @return  @c *this if successful
00162        *
00163        *  These functions use the stream's current locale (specifically, the
00164        *  @c num_get facet) to perform numeric formatting.
00165       */
00166       __ostream_type& 
00167       operator<<(long __n)
00168       { return _M_insert(__n); }
00169       
00170       __ostream_type& 
00171       operator<<(unsigned long __n)
00172       { return _M_insert(__n); }    
00173 
00174       __ostream_type& 
00175       operator<<(bool __n)
00176       { return _M_insert(__n); }
00177 
00178       __ostream_type& 
00179       operator<<(short __n);
00180 
00181       __ostream_type& 
00182       operator<<(unsigned short __n)
00183       {
00184     // _GLIBCXX_RESOLVE_LIB_DEFECTS
00185     // 117. basic_ostream uses nonexistent num_put member functions.
00186     return _M_insert(static_cast<unsigned long>(__n));
00187       }
00188 
00189       __ostream_type& 
00190       operator<<(int __n);
00191 
00192       __ostream_type& 
00193       operator<<(unsigned int __n)
00194       {
00195     // _GLIBCXX_RESOLVE_LIB_DEFECTS
00196     // 117. basic_ostream uses nonexistent num_put member functions.
00197     return _M_insert(static_cast<unsigned long>(__n));
00198       }
00199 
00200 #ifdef _GLIBCXX_USE_LONG_LONG
00201       __ostream_type& 
00202       operator<<(long long __n)
00203       { return _M_insert(__n); }
00204 
00205       __ostream_type& 
00206       operator<<(unsigned long long __n)
00207       { return _M_insert(__n); }    
00208 #endif
00209 
00210       __ostream_type& 
00211       operator<<(double __f)
00212       { return _M_insert(__f); }
00213 
00214       __ostream_type& 
00215       operator<<(float __f)
00216       {
00217     // _GLIBCXX_RESOLVE_LIB_DEFECTS
00218     // 117. basic_ostream uses nonexistent num_put member functions.
00219     return _M_insert(static_cast<double>(__f));
00220       }
00221 
00222       __ostream_type& 
00223       operator<<(long double __f)
00224       { return _M_insert(__f); }
00225 
00226       __ostream_type& 
00227       operator<<(const void* __p)
00228       { return _M_insert(__p); }
00229 
00230       /**
00231        *  @brief  Extracting from another streambuf.
00232        *  @param  sb  A pointer to a streambuf
00233        *
00234        *  This function behaves like one of the basic arithmetic extractors,
00235        *  in that it also constructs a sentry object and has the same error
00236        *  handling behavior.
00237        *
00238        *  If @a sb is NULL, the stream will set failbit in its error state.
00239        *
00240        *  Characters are extracted from @a sb and inserted into @c *this
00241        *  until one of the following occurs:
00242        *
00243        *  - the input stream reaches end-of-file,
00244        *  - insertion into the output sequence fails (in this case, the
00245        *    character that would have been inserted is not extracted), or
00246        *  - an exception occurs while getting a character from @a sb, which
00247        *    sets failbit in the error state
00248        *
00249        *  If the function inserts no characters, failbit is set.
00250       */
00251       __ostream_type& 
00252       operator<<(__streambuf_type* __sb);
00253       //@}
00254 
00255       // [27.6.2.6] unformatted output functions
00256       /**
00257        *  @name Unformatted Output Functions
00258        *
00259        *  All the unformatted output functions have some common behavior.
00260        *  Each starts by constructing a temporary object of type
00261        *  std::basic_ostream::sentry.  This has several effects, concluding
00262        *  with the setting of a status flag; see the sentry documentation
00263        *  for more.
00264        *
00265        *  If the sentry status is good, the function tries to generate
00266        *  whatever data is appropriate for the type of the argument.
00267        *
00268        *  If an exception is thrown during insertion, ios_base::badbit
00269        *  will be turned on in the stream's error state.  If badbit is on in
00270        *  the stream's exceptions mask, the exception will be rethrown
00271        *  without completing its actions.
00272       */
00273       //@{
00274       /**
00275        *  @brief  Simple insertion.
00276        *  @param  c  The character to insert.
00277        *  @return  *this
00278        *
00279        *  Tries to insert @a c.
00280        *
00281        *  @note  This function is not overloaded on signed char and
00282        *         unsigned char.
00283       */
00284       __ostream_type& 
00285       put(char_type __c);
00286 
00287       // Core write functionality, without sentry.
00288       void
00289       _M_write(const char_type* __s, streamsize __n)
00290       {
00291     const streamsize __put = this->rdbuf()->sputn(__s, __n);
00292     if (__put != __n)
00293       this->setstate(ios_base::badbit);
00294       }
00295 
00296       /**
00297        *  @brief  Character string insertion.
00298        *  @param  s  The array to insert.
00299        *  @param  n  Maximum number of characters to insert.
00300        *  @return  *this
00301        *
00302        *  Characters are copied from @a s and inserted into the stream until
00303        *  one of the following happens:
00304        *
00305        *  - @a n characters are inserted
00306        *  - inserting into the output sequence fails (in this case, badbit
00307        *    will be set in the stream's error state)
00308        *
00309        *  @note  This function is not overloaded on signed char and
00310        *         unsigned char.
00311       */
00312       __ostream_type& 
00313       write(const char_type* __s, streamsize __n);
00314       //@}
00315 
00316       /**
00317        *  @brief  Synchronizing the stream buffer.
00318        *  @return  *this
00319        *
00320        *  If @c rdbuf() is a null pointer, changes nothing.
00321        *
00322        *  Otherwise, calls @c rdbuf()->pubsync(), and if that returns -1,
00323        *  sets badbit.
00324       */
00325       __ostream_type& 
00326       flush();
00327 
00328       // [27.6.2.4] seek members
00329       /**
00330        *  @brief  Getting the current write position.
00331        *  @return  A file position object.
00332        *
00333        *  If @c fail() is not false, returns @c pos_type(-1) to indicate
00334        *  failure.  Otherwise returns @c rdbuf()->pubseekoff(0,cur,out).
00335       */
00336       pos_type 
00337       tellp();
00338 
00339       /**
00340        *  @brief  Changing the current write position.
00341        *  @param  pos  A file position object.
00342        *  @return  *this
00343        *
00344        *  If @c fail() is not true, calls @c rdbuf()->pubseekpos(pos).  If
00345        *  that function fails, sets failbit.
00346       */
00347       __ostream_type& 
00348       seekp(pos_type);
00349 
00350       /**
00351        *  @brief  Changing the current write position.
00352        *  @param  off  A file offset object.
00353        *  @param  dir  The direction in which to seek.
00354        *  @return  *this
00355        *
00356        *  If @c fail() is not true, calls @c rdbuf()->pubseekoff(off,dir).
00357        *  If that function fails, sets failbit.
00358       */
00359        __ostream_type& 
00360       seekp(off_type, ios_base::seekdir);
00361       
00362     protected:
00363       basic_ostream()
00364       { this->init(0); }
00365 
00366       template<typename _ValueT>
00367         __ostream_type&
00368         _M_insert(_ValueT __v);
00369     };
00370 
00371   /**
00372    *  @brief  Performs setup work for output streams.
00373    *
00374    *  Objects of this class are created before all of the standard
00375    *  inserters are run.  It is responsible for <em>exception-safe prefix and
00376    *  suffix operations</em>.
00377   */
00378   template <typename _CharT, typename _Traits>
00379     class basic_ostream<_CharT, _Traits>::sentry
00380     {
00381       // Data Members.
00382       bool              _M_ok;
00383       basic_ostream<_CharT, _Traits>&   _M_os;
00384       
00385     public:
00386       /**
00387        *  @brief  The constructor performs preparatory work.
00388        *  @param  os  The output stream to guard.
00389        *
00390        *  If the stream state is good (@a os.good() is true), then if the
00391        *  stream is tied to another output stream, @c is.tie()->flush()
00392        *  is called to synchronize the output sequences.
00393        *
00394        *  If the stream state is still good, then the sentry state becomes
00395        *  true (@a okay).
00396       */
00397       explicit
00398       sentry(basic_ostream<_CharT, _Traits>& __os);
00399 
00400       /**
00401        *  @brief  Possibly flushes the stream.
00402        *
00403        *  If @c ios_base::unitbuf is set in @c os.flags(), and
00404        *  @c std::uncaught_exception() is true, the sentry destructor calls
00405        *  @c flush() on the output stream.
00406       */
00407       ~sentry()
00408       {
00409     // XXX MT
00410     if (bool(_M_os.flags() & ios_base::unitbuf) && !uncaught_exception())
00411       {
00412         // Can't call flush directly or else will get into recursive lock.
00413         if (_M_os.rdbuf() && _M_os.rdbuf()->pubsync() == -1)
00414           _M_os.setstate(ios_base::badbit);
00415       }
00416       }
00417 
00418       /**
00419        *  @brief  Quick status checking.
00420        *  @return  The sentry state.
00421        *
00422        *  For ease of use, sentries may be converted to booleans.  The
00423        *  return value is that of the sentry state (true == okay).
00424       */
00425 #ifdef __GXX_EXPERIMENTAL_CXX0X__
00426       explicit
00427 #endif
00428       operator bool() const
00429       { return _M_ok; }
00430     };
00431 
00432   // [27.6.2.5.4] character insertion templates
00433   //@{
00434   /**
00435    *  @brief  Character inserters
00436    *  @param  out  An output stream.
00437    *  @param  c  A character.
00438    *  @return  out
00439    *
00440    *  Behaves like one of the formatted arithmetic inserters described in
00441    *  std::basic_ostream.  After constructing a sentry object with good
00442    *  status, this function inserts a single character and any required
00443    *  padding (as determined by [22.2.2.2.2]).  @c out.width(0) is then
00444    *  called.
00445    *
00446    *  If @a c is of type @c char and the character type of the stream is not
00447    *  @c char, the character is widened before insertion.
00448   */
00449   template<typename _CharT, typename _Traits>
00450     inline basic_ostream<_CharT, _Traits>&
00451     operator<<(basic_ostream<_CharT, _Traits>& __out, _CharT __c)
00452     { return __ostream_insert(__out, &__c, 1); }
00453 
00454   template<typename _CharT, typename _Traits>
00455     inline basic_ostream<_CharT, _Traits>&
00456     operator<<(basic_ostream<_CharT, _Traits>& __out, char __c)
00457     { return (__out << __out.widen(__c)); }
00458 
00459   // Specialization
00460   template <class _Traits> 
00461     inline basic_ostream<char, _Traits>&
00462     operator<<(basic_ostream<char, _Traits>& __out, char __c)
00463     { return __ostream_insert(__out, &__c, 1); }
00464 
00465   // Signed and unsigned
00466   template<class _Traits>
00467     inline basic_ostream<char, _Traits>&
00468     operator<<(basic_ostream<char, _Traits>& __out, signed char __c)
00469     { return (__out << static_cast<char>(__c)); }
00470   
00471   template<class _Traits>
00472     inline basic_ostream<char, _Traits>&
00473     operator<<(basic_ostream<char, _Traits>& __out, unsigned char __c)
00474     { return (__out << static_cast<char>(__c)); }
00475   //@}
00476   
00477   //@{
00478   /**
00479    *  @brief  String inserters
00480    *  @param  out  An output stream.
00481    *  @param  s  A character string.
00482    *  @return  out
00483    *  @pre  @a s must be a non-NULL pointer
00484    *
00485    *  Behaves like one of the formatted arithmetic inserters described in
00486    *  std::basic_ostream.  After constructing a sentry object with good
00487    *  status, this function inserts @c traits::length(s) characters starting
00488    *  at @a s, widened if necessary, followed by any required padding (as
00489    *  determined by [22.2.2.2.2]).  @c out.width(0) is then called.
00490   */
00491   template<typename _CharT, typename _Traits>
00492     inline basic_ostream<_CharT, _Traits>&
00493     operator<<(basic_ostream<_CharT, _Traits>& __out, const _CharT* __s)
00494     {
00495       if (!__s)
00496     __out.setstate(ios_base::badbit);
00497       else
00498     __ostream_insert(__out, __s,
00499              static_cast<streamsize>(_Traits::length(__s)));
00500       return __out;
00501     }
00502 
00503   template<typename _CharT, typename _Traits>
00504     basic_ostream<_CharT, _Traits> &
00505     operator<<(basic_ostream<_CharT, _Traits>& __out, const char* __s);
00506 
00507   // Partial specializations
00508   template<class _Traits>
00509     inline basic_ostream<char, _Traits>&
00510     operator<<(basic_ostream<char, _Traits>& __out, const char* __s)
00511     {
00512       if (!__s)
00513     __out.setstate(ios_base::badbit);
00514       else
00515     __ostream_insert(__out, __s,
00516              static_cast<streamsize>(_Traits::length(__s)));
00517       return __out;
00518     }
00519 
00520   // Signed and unsigned
00521   template<class _Traits>
00522     inline basic_ostream<char, _Traits>&
00523     operator<<(basic_ostream<char, _Traits>& __out, const signed char* __s)
00524     { return (__out << reinterpret_cast<const char*>(__s)); }
00525 
00526   template<class _Traits>
00527     inline basic_ostream<char, _Traits> &
00528     operator<<(basic_ostream<char, _Traits>& __out, const unsigned char* __s)
00529     { return (__out << reinterpret_cast<const char*>(__s)); }
00530   //@}
00531 
00532   // [27.6.2.7] standard basic_ostream manipulators
00533   /**
00534    *  @brief  Write a newline and flush the stream.
00535    *
00536    *  This manipulator is often mistakenly used when a simple newline is
00537    *  desired, leading to poor buffering performance.  See
00538    *  http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt11ch25s02.html
00539    *  for more on this subject.
00540   */
00541   template<typename _CharT, typename _Traits>
00542     inline basic_ostream<_CharT, _Traits>& 
00543     endl(basic_ostream<_CharT, _Traits>& __os)
00544     { return flush(__os.put(__os.widen('\n'))); }
00545 
00546   /**
00547    *  @brief  Write a null character into the output sequence.
00548    *
00549    *  <em>Null character</em> is @c CharT() by definition.  For CharT of @c char,
00550    *  this correctly writes the ASCII @c NUL character string terminator.
00551   */
00552   template<typename _CharT, typename _Traits>
00553     inline basic_ostream<_CharT, _Traits>& 
00554     ends(basic_ostream<_CharT, _Traits>& __os)
00555     { return __os.put(_CharT()); }
00556   
00557   /**
00558    *  @brief  Flushes the output stream.
00559    *
00560    *  This manipulator simply calls the stream's @c flush() member function.
00561   */
00562   template<typename _CharT, typename _Traits>
00563     inline basic_ostream<_CharT, _Traits>& 
00564     flush(basic_ostream<_CharT, _Traits>& __os)
00565     { return __os.flush(); }
00566 
00567 #ifdef __GXX_EXPERIMENTAL_CXX0X__
00568   // [27.7.2.9] Rvalue stream insertion
00569   /**
00570    *  @brief  Generic inserter for rvalue stream
00571    *  @param  os  An input stream.
00572    *  @param  x  A reference to the object being inserted.
00573    *  @return  os
00574    *
00575    *  This is just a forwarding function to allow insertion to
00576    *  rvalue streams since they won't bind to the inserter functions
00577    *  that take an lvalue reference.
00578   */
00579   template<typename _CharT, typename _Traits, typename _Tp>
00580     inline basic_ostream<_CharT, _Traits>&
00581     operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)
00582     { return (__os << __x); }
00583 #endif // __GXX_EXPERIMENTAL_CXX0X__
00584 
00585 _GLIBCXX_END_NAMESPACE_VERSION
00586 } // namespace
00587 
00588 #include <bits/ostream.tcc>
00589 
00590 #endif  /* _GLIBCXX_OSTREAM */