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