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