Home | History | Annotate | Download | only in include
      1 // Output streams -*- C++ -*-
      2 
      3 // Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
      4 // 2006, 2007, 2008, 2009, 2010, 2011
      5 // Free Software Foundation, Inc.
      6 //
      7 // This file is part of the GNU ISO C++ Library.  This library is free
      8 // software; you can redistribute it and/or modify it under the
      9 // terms of the GNU General Public License as published by the
     10 // Free Software Foundation; either version 3, or (at your option)
     11 // any later version.
     12 
     13 // This library is distributed in the hope that it will be useful,
     14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
     15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     16 // GNU General Public License for more details.
     17 
     18 // Under Section 7 of GPL version 3, you are granted additional
     19 // permissions described in the GCC Runtime Library Exception, version
     20 // 3.1, as published by the Free Software Foundation.
     21 
     22 // You should have received a copy of the GNU General Public License and
     23 // a copy of the GCC Runtime Library Exception along with this program;
     24 // see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
     25 // <http://www.gnu.org/licenses/>.
     26 
     27 /** @file include/ostream
     28  *  This is a Standard C++ Library header.
     29  */
     30 
     31 //
     32 // ISO C++ 14882: 27.6.2  Output streams
     33 //
     34 
     35 #ifndef _GLIBCXX_OSTREAM
     36 #define _GLIBCXX_OSTREAM 1
     37 
     38 #pragma GCC system_header
     39 
     40 #include <ios>
     41 #include <bits/ostream_insert.h>
     42 
     43 namespace std _GLIBCXX_VISIBILITY(default)
     44 {
     45 _GLIBCXX_BEGIN_NAMESPACE_VERSION
     46 
     47   /**
     48    *  @brief  Template class basic_ostream.
     49    *  @ingroup io
     50    *
     51    *  This is the base class for all output streams.  It provides text
     52    *  formatting of all builtin types, and communicates with any class
     53    *  derived from basic_streambuf to do the actual output.
     54   */
     55   template<typename _CharT, typename _Traits>
     56     class basic_ostream : virtual public basic_ios<_CharT, _Traits>
     57     {
     58     public:
     59       // Types (inherited from basic_ios):
     60       typedef _CharT			 		char_type;
     61       typedef typename _Traits::int_type 		int_type;
     62       typedef typename _Traits::pos_type 		pos_type;
     63       typedef typename _Traits::off_type 		off_type;
     64       typedef _Traits			 		traits_type;
     65 
     66       // Non-standard Types:
     67       typedef basic_streambuf<_CharT, _Traits> 		__streambuf_type;
     68       typedef basic_ios<_CharT, _Traits>		__ios_type;
     69       typedef basic_ostream<_CharT, _Traits>		__ostream_type;
     70       typedef num_put<_CharT, ostreambuf_iterator<_CharT, _Traits> >
     71       							__num_put_type;
     72       typedef ctype<_CharT>	      			__ctype_type;
     73 
     74       /**
     75        *  @brief  Base constructor.
     76        *
     77        *  This ctor is almost never called by the user directly, rather from
     78        *  derived classes' initialization lists, which pass a pointer to
     79        *  their own stream buffer.
     80       */
     81       explicit
     82       basic_ostream(__streambuf_type* __sb)
     83       { this->init(__sb); }
     84 
     85       /**
     86        *  @brief  Base destructor.
     87        *
     88        *  This does very little apart from providing a virtual base dtor.
     89       */
     90       virtual
     91       ~basic_ostream() { }
     92 
     93       /// Safe prefix/suffix operations.
     94       class sentry;
     95       friend class sentry;
     96 
     97       //@{
     98       /**
     99        *  @brief  Interface for manipulators.
    100        *
    101        *  Manipulators such as @c std::endl and @c std::hex use these
    102        *  functions in constructs like "std::cout << std::endl".  For more
    103        *  information, see the iomanip header.
    104       */
    105       __ostream_type&
    106       operator<<(__ostream_type& (*__pf)(__ostream_type&))
    107       {
    108 	// _GLIBCXX_RESOLVE_LIB_DEFECTS
    109 	// DR 60. What is a formatted input function?
    110 	// The inserters for manipulators are *not* formatted output functions.
    111 	return __pf(*this);
    112       }
    113 
    114       __ostream_type&
    115       operator<<(__ios_type& (*__pf)(__ios_type&))
    116       {
    117 	// _GLIBCXX_RESOLVE_LIB_DEFECTS
    118 	// DR 60. What is a formatted input function?
    119 	// The inserters for manipulators are *not* formatted output functions.
    120 	__pf(*this);
    121 	return *this;
    122       }
    123 
    124       __ostream_type&
    125       operator<<(ios_base& (*__pf) (ios_base&))
    126       {
    127 	// _GLIBCXX_RESOLVE_LIB_DEFECTS
    128 	// DR 60. What is a formatted input function?
    129 	// The inserters for manipulators are *not* formatted output functions.
    130 	__pf(*this);
    131 	return *this;
    132       }
    133       //@}
    134 
    135       //@{
    136       /**
    137        *  @name Inserters
    138        *
    139        *  All the @c operator<< functions (aka <em>formatted output
    140        *  functions</em>) have some common behavior.  Each starts by
    141        *  constructing a temporary object of type std::basic_ostream::sentry.
    142        *  This can have several effects, concluding with the setting of a
    143        *  status flag; see the sentry documentation for more.
    144        *
    145        *  If the sentry status is good, the function tries to generate
    146        *  whatever data is appropriate for the type of the argument.
    147        *
    148        *  If an exception is thrown during insertion, ios_base::badbit
    149        *  will be turned on in the stream's error state without causing an
    150        *  ios_base::failure to be thrown.  The original exception will then
    151        *  be rethrown.
    152       */
    153 
    154       //@{
    155       /**
    156        *  @brief Integer arithmetic inserters
    157        *  @param  __n A variable of builtin integral type.
    158        *  @return  @c *this if successful
    159        *
    160        *  These functions use the stream's current locale (specifically, the
    161        *  @c num_get facet) to perform numeric formatting.
    162       */
    163       __ostream_type&
    164       operator<<(long __n)
    165       { return _M_insert(__n); }
    166 
    167       __ostream_type&
    168       operator<<(unsigned long __n)
    169       { return _M_insert(__n); }
    170 
    171       __ostream_type&
    172       operator<<(bool __n)
    173       { return _M_insert(__n); }
    174 
    175       __ostream_type&
    176       operator<<(short __n);
    177 
    178       __ostream_type&
    179       operator<<(unsigned short __n)
    180       {
    181 	// _GLIBCXX_RESOLVE_LIB_DEFECTS
    182 	// 117. basic_ostream uses nonexistent num_put member functions.
    183 	return _M_insert(static_cast<unsigned long>(__n));
    184       }
    185 
    186       __ostream_type&
    187       operator<<(int __n);
    188 
    189       __ostream_type&
    190       operator<<(unsigned int __n)
    191       {
    192 	// _GLIBCXX_RESOLVE_LIB_DEFECTS
    193 	// 117. basic_ostream uses nonexistent num_put member functions.
    194 	return _M_insert(static_cast<unsigned long>(__n));
    195       }
    196 
    197 #ifdef _GLIBCXX_USE_LONG_LONG
    198       __ostream_type&
    199       operator<<(long long __n)
    200       { return _M_insert(__n); }
    201 
    202       __ostream_type&
    203       operator<<(unsigned long long __n)
    204       { return _M_insert(__n); }
    205 #endif
    206       //@}
    207 
    208       //@{
    209       /**
    210        *  @brief  Floating point arithmetic inserters
    211        *  @param  __f A variable of builtin floating point type.
    212        *  @return  @c *this if successful
    213        *
    214        *  These functions use the stream's current locale (specifically, the
    215        *  @c num_get facet) to perform numeric formatting.
    216       */
    217       __ostream_type&
    218       operator<<(double __f)
    219       { return _M_insert(__f); }
    220 
    221       __ostream_type&
    222       operator<<(float __f)
    223       {
    224 	// _GLIBCXX_RESOLVE_LIB_DEFECTS
    225 	// 117. basic_ostream uses nonexistent num_put member functions.
    226 	return _M_insert(static_cast<double>(__f));
    227       }
    228 
    229       __ostream_type&
    230       operator<<(long double __f)
    231       { return _M_insert(__f); }
    232       //@}
    233 
    234       /**
    235        *  @brief  Pointer arithmetic inserters
    236        *  @param  __p A variable of pointer type.
    237        *  @return  @c *this if successful
    238        *
    239        *  These functions use the stream's current locale (specifically, the
    240        *  @c num_get facet) to perform numeric formatting.
    241       */
    242       __ostream_type&
    243       operator<<(const void* __p)
    244       { return _M_insert(__p); }
    245 
    246       /**
    247        *  @brief  Extracting from another streambuf.
    248        *  @param  __sb  A pointer to a streambuf
    249        *
    250        *  This function behaves like one of the basic arithmetic extractors,
    251        *  in that it also constructs a sentry object and has the same error
    252        *  handling behavior.
    253        *
    254        *  If @p __sb is NULL, the stream will set failbit in its error state.
    255        *
    256        *  Characters are extracted from @p __sb and inserted into @c *this
    257        *  until one of the following occurs:
    258        *
    259        *  - the input stream reaches end-of-file,
    260        *  - insertion into the output sequence fails (in this case, the
    261        *    character that would have been inserted is not extracted), or
    262        *  - an exception occurs while getting a character from @p __sb, which
    263        *    sets failbit in the error state
    264        *
    265        *  If the function inserts no characters, failbit is set.
    266       */
    267       __ostream_type&
    268       operator<<(__streambuf_type* __sb);
    269       //@}
    270 
    271       //@{
    272       /**
    273        *  @name Unformatted Output Functions
    274        *
    275        *  All the unformatted output functions have some common behavior.
    276        *  Each starts by constructing a temporary object of type
    277        *  std::basic_ostream::sentry.  This has several effects, concluding
    278        *  with the setting of a status flag; see the sentry documentation
    279        *  for more.
    280        *
    281        *  If the sentry status is good, the function tries to generate
    282        *  whatever data is appropriate for the type of the argument.
    283        *
    284        *  If an exception is thrown during insertion, ios_base::badbit
    285        *  will be turned on in the stream's error state.  If badbit is on in
    286        *  the stream's exceptions mask, the exception will be rethrown
    287        *  without completing its actions.
    288       */
    289 
    290       /**
    291        *  @brief  Simple insertion.
    292        *  @param  __c  The character to insert.
    293        *  @return  *this
    294        *
    295        *  Tries to insert @p __c.
    296        *
    297        *  @note  This function is not overloaded on signed char and
    298        *         unsigned char.
    299       */
    300       __ostream_type&
    301       put(char_type __c);
    302 
    303       /**
    304        *  @brief  Core write functionality, without sentry.
    305        *  @param  __s  The array to insert.
    306        *  @param  __n  Maximum number of characters to insert.
    307       */
    308       void
    309       _M_write(const char_type* __s, streamsize __n)
    310       {
    311 	const streamsize __put = this->rdbuf()->sputn(__s, __n);
    312 	if (__put != __n)
    313 	  this->setstate(ios_base::badbit);
    314       }
    315 
    316       /**
    317        *  @brief  Character string insertion.
    318        *  @param  __s  The array to insert.
    319        *  @param  __n  Maximum number of characters to insert.
    320        *  @return  *this
    321        *
    322        *  Characters are copied from @p __s and inserted into the stream until
    323        *  one of the following happens:
    324        *
    325        *  - @p __n characters are inserted
    326        *  - inserting into the output sequence fails (in this case, badbit
    327        *    will be set in the stream's error state)
    328        *
    329        *  @note  This function is not overloaded on signed char and
    330        *         unsigned char.
    331       */
    332       __ostream_type&
    333       write(const char_type* __s, streamsize __n);
    334       //@}
    335 
    336       /**
    337        *  @brief  Synchronizing the stream buffer.
    338        *  @return  *this
    339        *
    340        *  If @c rdbuf() is a null pointer, changes nothing.
    341        *
    342        *  Otherwise, calls @c rdbuf()->pubsync(), and if that returns -1,
    343        *  sets badbit.
    344       */
    345       __ostream_type&
    346       flush();
    347 
    348       /**
    349        *  @brief  Getting the current write position.
    350        *  @return  A file position object.
    351        *
    352        *  If @c fail() is not false, returns @c pos_type(-1) to indicate
    353        *  failure.  Otherwise returns @c rdbuf()->pubseekoff(0,cur,out).
    354       */
    355       pos_type
    356       tellp();
    357 
    358       /**
    359        *  @brief  Changing the current write position.
    360        *  @param  __pos  A file position object.
    361        *  @return  *this
    362        *
    363        *  If @c fail() is not true, calls @c rdbuf()->pubseekpos(pos).  If
    364        *  that function fails, sets failbit.
    365       */
    366       __ostream_type&
    367       seekp(pos_type);
    368 
    369       /**
    370        *  @brief  Changing the current write position.
    371        *  @param  __off  A file offset object.
    372        *  @param  __dir  The direction in which to seek.
    373        *  @return  *this
    374        *
    375        *  If @c fail() is not true, calls @c rdbuf()->pubseekoff(off,dir).
    376        *  If that function fails, sets failbit.
    377       */
    378        __ostream_type&
    379       seekp(off_type, ios_base::seekdir);
    380 
    381     protected:
    382       basic_ostream()
    383       { this->init(0); }
    384 
    385       template<typename _ValueT>
    386 	__ostream_type&
    387 	_M_insert(_ValueT __v);
    388     };
    389 
    390   /**
    391    *  @brief  Performs setup work for output streams.
    392    *
    393    *  Objects of this class are created before all of the standard
    394    *  inserters are run.  It is responsible for <em>exception-safe prefix and
    395    *  suffix operations</em>.
    396   */
    397   template <typename _CharT, typename _Traits>
    398     class basic_ostream<_CharT, _Traits>::sentry
    399     {
    400       // Data Members.
    401       bool 				_M_ok;
    402       basic_ostream<_CharT, _Traits>& 	_M_os;
    403 
    404     public:
    405       /**
    406        *  @brief  The constructor performs preparatory work.
    407        *  @param  __os  The output stream to guard.
    408        *
    409        *  If the stream state is good (@a __os.good() is true), then if the
    410        *  stream is tied to another output stream, @c is.tie()->flush()
    411        *  is called to synchronize the output sequences.
    412        *
    413        *  If the stream state is still good, then the sentry state becomes
    414        *  true (@a okay).
    415       */
    416       explicit
    417       sentry(basic_ostream<_CharT, _Traits>& __os);
    418 
    419       /**
    420        *  @brief  Possibly flushes the stream.
    421        *
    422        *  If @c ios_base::unitbuf is set in @c os.flags(), and
    423        *  @c std::uncaught_exception() is true, the sentry destructor calls
    424        *  @c flush() on the output stream.
    425       */
    426       ~sentry()
    427       {
    428 	// XXX MT
    429 	if (bool(_M_os.flags() & ios_base::unitbuf) && !uncaught_exception())
    430 	  {
    431 	    // Can't call flush directly or else will get into recursive lock.
    432 	    if (_M_os.rdbuf() && _M_os.rdbuf()->pubsync() == -1)
    433 	      _M_os.setstate(ios_base::badbit);
    434 	  }
    435       }
    436 
    437       /**
    438        *  @brief  Quick status checking.
    439        *  @return  The sentry state.
    440        *
    441        *  For ease of use, sentries may be converted to booleans.  The
    442        *  return value is that of the sentry state (true == okay).
    443       */
    444 #ifdef __GXX_EXPERIMENTAL_CXX0X__
    445       explicit
    446 #endif
    447       operator bool() const
    448       { return _M_ok; }
    449     };
    450 
    451   //@{
    452   /**
    453    *  @brief  Character inserters
    454    *  @param  __out  An output stream.
    455    *  @param  __c  A character.
    456    *  @return  out
    457    *
    458    *  Behaves like one of the formatted arithmetic inserters described in
    459    *  std::basic_ostream.  After constructing a sentry object with good
    460    *  status, this function inserts a single character and any required
    461    *  padding (as determined by [22.2.2.2.2]).  @c __out.width(0) is then
    462    *  called.
    463    *
    464    *  If @p __c is of type @c char and the character type of the stream is not
    465    *  @c char, the character is widened before insertion.
    466   */
    467   template<typename _CharT, typename _Traits>
    468     inline basic_ostream<_CharT, _Traits>&
    469     operator<<(basic_ostream<_CharT, _Traits>& __out, _CharT __c)
    470     { return __ostream_insert(__out, &__c, 1); }
    471 
    472   template<typename _CharT, typename _Traits>
    473     inline basic_ostream<_CharT, _Traits>&
    474     operator<<(basic_ostream<_CharT, _Traits>& __out, char __c)
    475     { return (__out << __out.widen(__c)); }
    476 
    477   // Specialization
    478   template <class _Traits>
    479     inline basic_ostream<char, _Traits>&
    480     operator<<(basic_ostream<char, _Traits>& __out, char __c)
    481     { return __ostream_insert(__out, &__c, 1); }
    482 
    483   // Signed and unsigned
    484   template<class _Traits>
    485     inline basic_ostream<char, _Traits>&
    486     operator<<(basic_ostream<char, _Traits>& __out, signed char __c)
    487     { return (__out << static_cast<char>(__c)); }
    488 
    489   template<class _Traits>
    490     inline basic_ostream<char, _Traits>&
    491     operator<<(basic_ostream<char, _Traits>& __out, unsigned char __c)
    492     { return (__out << static_cast<char>(__c)); }
    493   //@}
    494 
    495   //@{
    496   /**
    497    *  @brief  String inserters
    498    *  @param  __out  An output stream.
    499    *  @param  __s  A character string.
    500    *  @return  out
    501    *  @pre  @p __s must be a non-NULL pointer
    502    *
    503    *  Behaves like one of the formatted arithmetic inserters described in
    504    *  std::basic_ostream.  After constructing a sentry object with good
    505    *  status, this function inserts @c traits::length(__s) characters starting
    506    *  at @p __s, widened if necessary, followed by any required padding (as
    507    *  determined by [22.2.2.2.2]).  @c __out.width(0) is then called.
    508   */
    509   template<typename _CharT, typename _Traits>
    510     inline basic_ostream<_CharT, _Traits>&
    511     operator<<(basic_ostream<_CharT, _Traits>& __out, const _CharT* __s)
    512     {
    513       if (!__s)
    514 	__out.setstate(ios_base::badbit);
    515       else
    516 	__ostream_insert(__out, __s,
    517 			 static_cast<streamsize>(_Traits::length(__s)));
    518       return __out;
    519     }
    520 
    521   template<typename _CharT, typename _Traits>
    522     basic_ostream<_CharT, _Traits> &
    523     operator<<(basic_ostream<_CharT, _Traits>& __out, const char* __s);
    524 
    525   // Partial specializations
    526   template<class _Traits>
    527     inline basic_ostream<char, _Traits>&
    528     operator<<(basic_ostream<char, _Traits>& __out, const char* __s)
    529     {
    530       if (!__s)
    531 	__out.setstate(ios_base::badbit);
    532       else
    533 	__ostream_insert(__out, __s,
    534 			 static_cast<streamsize>(_Traits::length(__s)));
    535       return __out;
    536     }
    537 
    538   // Signed and unsigned
    539   template<class _Traits>
    540     inline basic_ostream<char, _Traits>&
    541     operator<<(basic_ostream<char, _Traits>& __out, const signed char* __s)
    542     { return (__out << reinterpret_cast<const char*>(__s)); }
    543 
    544   template<class _Traits>
    545     inline basic_ostream<char, _Traits> &
    546     operator<<(basic_ostream<char, _Traits>& __out, const unsigned char* __s)
    547     { return (__out << reinterpret_cast<const char*>(__s)); }
    548   //@}
    549 
    550   // Standard basic_ostream manipulators
    551 
    552   /**
    553    *  @brief  Write a newline and flush the stream.
    554    *
    555    *  This manipulator is often mistakenly used when a simple newline is
    556    *  desired, leading to poor buffering performance.  See
    557    *  http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt11ch25s02.html
    558    *  for more on this subject.
    559   */
    560   template<typename _CharT, typename _Traits>
    561     inline basic_ostream<_CharT, _Traits>&
    562     endl(basic_ostream<_CharT, _Traits>& __os)
    563     { return flush(__os.put(__os.widen('\n'))); }
    564 
    565   /**
    566    *  @brief  Write a null character into the output sequence.
    567    *
    568    *  <em>Null character</em> is @c CharT() by definition.  For CharT
    569    *  of @c char, this correctly writes the ASCII @c NUL character
    570    *  string terminator.
    571   */
    572   template<typename _CharT, typename _Traits>
    573     inline basic_ostream<_CharT, _Traits>&
    574     ends(basic_ostream<_CharT, _Traits>& __os)
    575     { return __os.put(_CharT()); }
    576 
    577   /**
    578    *  @brief  Flushes the output stream.
    579    *
    580    *  This manipulator simply calls the stream's @c flush() member function.
    581   */
    582   template<typename _CharT, typename _Traits>
    583     inline basic_ostream<_CharT, _Traits>&
    584     flush(basic_ostream<_CharT, _Traits>& __os)
    585     { return __os.flush(); }
    586 
    587 #ifdef __GXX_EXPERIMENTAL_CXX0X__
    588   /**
    589    *  @brief  Generic inserter for rvalue stream
    590    *  @param  __os  An input stream.
    591    *  @param  __x  A reference to the object being inserted.
    592    *  @return  os
    593    *
    594    *  This is just a forwarding function to allow insertion to
    595    *  rvalue streams since they won't bind to the inserter functions
    596    *  that take an lvalue reference.
    597   */
    598   template<typename _CharT, typename _Traits, typename _Tp>
    599     inline basic_ostream<_CharT, _Traits>&
    600     operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)
    601     { return (__os << __x); }
    602 #endif // __GXX_EXPERIMENTAL_CXX0X__
    603 
    604 _GLIBCXX_END_NAMESPACE_VERSION
    605 } // namespace std
    606 
    607 #include <bits/ostream.tcc>
    608 
    609 #endif	/* _GLIBCXX_OSTREAM */
    610