libstdc++
ostream
Go to the documentation of this file.
1// Output streams -*- C++ -*-
2
3// Copyright (C) 1997-2025 Free Software Foundation, Inc.
4//
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
9// any later version.
10
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
19
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
24
25/** @file include/ostream
26 * This is a Standard C++ Library header.
27 */
28
29//
30// ISO C++ 14882: 27.6.2 Output streams
31//
32
33#ifndef _GLIBCXX_OSTREAM
34#define _GLIBCXX_OSTREAM 1
35
36#ifdef _GLIBCXX_SYSHDR
37#pragma GCC system_header
38#endif
39
40#include <bits/requires_hosted.h> // iostreams
41
42#include <ios>
43#include <bits/ostream_insert.h>
44#if __cplusplus > 202002L
45# include <format>
46#endif
47
48# define __glibcxx_want_print
49#include <bits/version.h> // __glibcxx_syncbuf
50
51namespace std _GLIBCXX_VISIBILITY(default)
52{
53_GLIBCXX_BEGIN_NAMESPACE_VERSION
54
55 /**
56 * @brief Template class basic_ostream.
57 * @ingroup io
58 *
59 * @tparam _CharT Type of character stream.
60 * @tparam _Traits Traits for character type, defaults to
61 * char_traits<_CharT>.
62 *
63 * This is the base class for all output streams. It provides text
64 * formatting of all builtin types, and communicates with any class
65 * derived from basic_streambuf to do the actual output.
66 */
67 template<typename _CharT, typename _Traits>
68 class basic_ostream : virtual public basic_ios<_CharT, _Traits>
69 {
70 public:
71 // Types (inherited from basic_ios):
72 typedef _CharT char_type;
73 typedef typename _Traits::int_type int_type;
74 typedef typename _Traits::pos_type pos_type;
75 typedef typename _Traits::off_type off_type;
76 typedef _Traits traits_type;
77
78 // Non-standard Types:
79 typedef basic_streambuf<_CharT, _Traits> __streambuf_type;
80 typedef basic_ios<_CharT, _Traits> __ios_type;
81 typedef basic_ostream<_CharT, _Traits> __ostream_type;
82 typedef num_put<_CharT, ostreambuf_iterator<_CharT, _Traits> >
83 __num_put_type;
84 typedef ctype<_CharT> __ctype_type;
85
86 /**
87 * @brief Base constructor.
88 *
89 * This ctor is almost never called by the user directly, rather from
90 * derived classes' initialization lists, which pass a pointer to
91 * their own stream buffer.
92 */
93 explicit
94 basic_ostream(__streambuf_type* __sb)
95 { this->init(__sb); }
96
97 /**
98 * @brief Base destructor.
99 *
100 * This does very little apart from providing a virtual base dtor.
101 */
102 virtual
103 ~basic_ostream() { }
104
105 /// Safe prefix/suffix operations.
106 class sentry;
107 friend class sentry;
108
109 ///@{
110 /**
111 * @brief Interface for manipulators.
112 *
113 * Manipulators such as @c std::endl and @c std::hex use these
114 * functions in constructs like "std::cout << std::endl". For more
115 * information, see the iomanip header.
116 */
117 __ostream_type&
118 operator<<(__ostream_type& (*__pf)(__ostream_type&))
119 {
120 // _GLIBCXX_RESOLVE_LIB_DEFECTS
121 // DR 60. What is a formatted input function?
122 // The inserters for manipulators are *not* formatted output functions.
123 return __pf(*this);
124 }
125
126 __ostream_type&
127 operator<<(__ios_type& (*__pf)(__ios_type&))
128 {
129 // _GLIBCXX_RESOLVE_LIB_DEFECTS
130 // DR 60. What is a formatted input function?
131 // The inserters for manipulators are *not* formatted output functions.
132 __pf(*this);
133 return *this;
134 }
135
136 __ostream_type&
137 operator<<(ios_base& (*__pf) (ios_base&))
138 {
139 // _GLIBCXX_RESOLVE_LIB_DEFECTS
140 // DR 60. What is a formatted input function?
141 // The inserters for manipulators are *not* formatted output functions.
142 __pf(*this);
143 return *this;
144 }
145 ///@}
146
147 ///@{
148 /**
149 * @name Inserters
150 *
151 * All the @c operator<< functions (aka <em>formatted output
152 * functions</em>) have some common behavior. Each starts by
153 * constructing a temporary object of type std::basic_ostream::sentry.
154 * This can have several effects, concluding with the setting of a
155 * status flag; see the sentry documentation for more.
156 *
157 * If the sentry status is good, the function tries to generate
158 * whatever data is appropriate for the type of the argument.
159 *
160 * If an exception is thrown during insertion, ios_base::badbit
161 * will be turned on in the stream's error state without causing an
162 * ios_base::failure to be thrown. The original exception will then
163 * be rethrown.
164 */
165
166 ///@{
167 /**
168 * @brief Integer arithmetic inserters
169 * @param __n A variable of builtin integral type.
170 * @return @c *this if successful
171 *
172 * These functions use the stream's current locale (specifically, the
173 * @c num_get facet) to perform numeric formatting.
174 */
175 __ostream_type&
176 operator<<(long __n)
177 { return _M_insert(__n); }
178
179 __ostream_type&
180 operator<<(unsigned long __n)
181 { return _M_insert(__n); }
182
183 __ostream_type&
184 operator<<(bool __n)
185 { return _M_insert(__n); }
186
187 __ostream_type&
188 operator<<(short __n);
189
190 __ostream_type&
191 operator<<(unsigned short __n)
192 {
193 // _GLIBCXX_RESOLVE_LIB_DEFECTS
194 // 117. basic_ostream uses nonexistent num_put member functions.
195 return _M_insert(static_cast<unsigned long>(__n));
196 }
197
198 __ostream_type&
199 operator<<(int __n);
200
201 __ostream_type&
202 operator<<(unsigned int __n)
203 {
204 // _GLIBCXX_RESOLVE_LIB_DEFECTS
205 // 117. basic_ostream uses nonexistent num_put member functions.
206 return _M_insert(static_cast<unsigned long>(__n));
207 }
208
209#ifdef _GLIBCXX_USE_LONG_LONG
210#pragma GCC diagnostic push
211#pragma GCC diagnostic ignored "-Wlong-long"
212 __ostream_type&
213 operator<<(long long __n)
214 { return _M_insert(__n); }
215
216 __ostream_type&
217 operator<<(unsigned long long __n)
218 { return _M_insert(__n); }
219#pragma GCC diagnostic pop
220#endif
221 ///@}
222
223 ///@{
224 /**
225 * @brief Floating point arithmetic inserters
226 * @param __f A variable of builtin floating point type.
227 * @return @c *this if successful
228 *
229 * These functions use the stream's current locale (specifically, the
230 * @c num_get facet) to perform numeric formatting.
231 */
232 __ostream_type&
233 operator<<(double __f)
234 { return _M_insert(__f); }
235
236 __ostream_type&
237 operator<<(float __f)
238 {
239 // _GLIBCXX_RESOLVE_LIB_DEFECTS
240 // 117. basic_ostream uses nonexistent num_put member functions.
241 return _M_insert(_S_cast_flt<double>(__f));
242 }
243
244 __ostream_type&
245 operator<<(long double __f)
246 { return _M_insert(__f); }
247 ///@}
248
249#if defined(__STDCPP_FLOAT16_T__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
250 __attribute__((__always_inline__))
251 __ostream_type&
252 operator<<(_Float16 __f)
253 {
254 return _M_insert(_S_cast_flt<double>(__f));
255 }
256#endif
257
258#if defined(__STDCPP_FLOAT32_T__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
259 __attribute__((__always_inline__))
260 __ostream_type&
261 operator<<(_Float32 __f)
262 {
263 return _M_insert(_S_cast_flt<double>(__f));
264 }
265#endif
266
267#if defined(__STDCPP_FLOAT64_T__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
268 __attribute__((__always_inline__))
269 __ostream_type&
270 operator<<(_Float64 __f)
271 {
272 return _M_insert(_S_cast_flt<double>(__f));
273 }
274#endif
275
276#if defined(__STDCPP_FLOAT128_T__) && defined(_GLIBCXX_LDOUBLE_IS_IEEE_BINARY128)
277 __attribute__((__always_inline__))
278 __ostream_type&
279 operator<<(_Float128 __f)
280 {
281 return _M_insert(_S_cast_flt<long double>(__f));
282 }
283#endif
284
285#if defined(__STDCPP_BFLOAT16_T__) && defined(_GLIBCXX_DOUBLE_IS_IEEE_BINARY64)
286 __attribute__((__always_inline__))
287 __ostream_type&
288 operator<<(__gnu_cxx::__bfloat16_t __f)
289 {
290 return _M_insert(_S_cast_flt<double>(__f));
291 }
292#endif
293
294 /**
295 * @brief Pointer arithmetic inserters
296 * @param __p A variable of pointer type.
297 * @return @c *this if successful
298 *
299 * These functions use the stream's current locale (specifically, the
300 * @c num_get facet) to perform numeric formatting.
301 */
302 __ostream_type&
303 operator<<(const void* __p)
304 { return _M_insert(__p); }
305
306#if __cplusplus >= 201703L
307 __ostream_type&
308 operator<<(nullptr_t)
309 { return *this << "nullptr"; }
310#endif
311
312#if __cplusplus > 202002L
313 __attribute__((__always_inline__))
314 __ostream_type&
315 operator<<(const volatile void* __p)
316 { return _M_insert(const_cast<const void*>(__p)); }
317#endif
318
319 /**
320 * @brief Extracting from another streambuf.
321 * @param __sb A pointer to a streambuf
322 *
323 * This function behaves like one of the basic arithmetic extractors,
324 * in that it also constructs a sentry object and has the same error
325 * handling behavior.
326 *
327 * If @p __sb is NULL, the stream will set failbit in its error state.
328 *
329 * Characters are extracted from @p __sb and inserted into @c *this
330 * until one of the following occurs:
331 *
332 * - the input stream reaches end-of-file,
333 * - insertion into the output sequence fails (in this case, the
334 * character that would have been inserted is not extracted), or
335 * - an exception occurs while getting a character from @p __sb, which
336 * sets failbit in the error state
337 *
338 * If the function inserts no characters, failbit is set.
339 */
340 __ostream_type&
341 operator<<(__streambuf_type* __sb);
342 ///@}
343
344 ///@{
345 /**
346 * @name Unformatted Output Functions
347 *
348 * All the unformatted output functions have some common behavior.
349 * Each starts by constructing a temporary object of type
350 * std::basic_ostream::sentry. This has several effects, concluding
351 * with the setting of a status flag; see the sentry documentation
352 * for more.
353 *
354 * If the sentry status is good, the function tries to generate
355 * whatever data is appropriate for the type of the argument.
356 *
357 * If an exception is thrown during insertion, ios_base::badbit
358 * will be turned on in the stream's error state. If badbit is on in
359 * the stream's exceptions mask, the exception will be rethrown
360 * without completing its actions.
361 */
362
363 /**
364 * @brief Simple insertion.
365 * @param __c The character to insert.
366 * @return *this
367 *
368 * Tries to insert @p __c.
369 *
370 * @note This function is not overloaded on signed char and
371 * unsigned char.
372 */
373 __ostream_type&
374 put(char_type __c);
375
376 /**
377 * @brief Character string insertion.
378 * @param __s The array to insert.
379 * @param __n Maximum number of characters to insert.
380 * @return *this
381 *
382 * Characters are copied from @p __s and inserted into the stream until
383 * one of the following happens:
384 *
385 * - @p __n characters are inserted
386 * - inserting into the output sequence fails (in this case, badbit
387 * will be set in the stream's error state)
388 *
389 * @note This function is not overloaded on signed char and
390 * unsigned char.
391 */
392 __ostream_type&
393 write(const char_type* __s, streamsize __n);
394 ///@}
395
396 /**
397 * @brief Synchronizing the stream buffer.
398 * @return *this
399 *
400 * If @c rdbuf() is a null pointer, changes nothing.
401 *
402 * Otherwise, calls @c rdbuf()->pubsync(), and if that returns -1,
403 * sets badbit.
404 */
405 __ostream_type&
406 flush();
407
408 /**
409 * @brief Getting the current write position.
410 * @return A file position object.
411 *
412 * If @c fail() is not false, returns @c pos_type(-1) to indicate
413 * failure. Otherwise returns @c rdbuf()->pubseekoff(0,cur,out).
414 */
415 pos_type
416 tellp();
417
418 /**
419 * @brief Changing the current write position.
420 * @param __pos A file position object.
421 * @return *this
422 *
423 * If @c fail() is not true, calls @c rdbuf()->pubseekpos(pos). If
424 * that function fails, sets failbit.
425 */
426 __ostream_type&
427 seekp(pos_type);
428
429 /**
430 * @brief Changing the current write position.
431 * @param __off A file offset object.
432 * @param __dir The direction in which to seek.
433 * @return *this
434 *
435 * If @c fail() is not true, calls @c rdbuf()->pubseekoff(off,dir).
436 * If that function fails, sets failbit.
437 */
438 __ostream_type&
439 seekp(off_type, ios_base::seekdir);
440
441 protected:
442 basic_ostream()
443 { this->init(0); }
444
445#if __cplusplus >= 201103L
446 // Non-standard constructor that does not call init()
447 basic_ostream(basic_iostream<_CharT, _Traits>&) { }
448
449 basic_ostream(const basic_ostream&) = delete;
450
451 basic_ostream(basic_ostream&& __rhs)
452 : __ios_type()
453 { __ios_type::move(__rhs); }
454
455 // 27.7.3.3 Assign/swap
456
457 basic_ostream& operator=(const basic_ostream&) = delete;
458
459 basic_ostream&
460 operator=(basic_ostream&& __rhs)
461 {
462 swap(__rhs);
463 return *this;
464 }
465
466 void
467 swap(basic_ostream& __rhs)
468 { __ios_type::swap(__rhs); }
469#endif
470
471 template<typename _ValueT>
472 __ostream_type&
473 _M_insert(_ValueT __v);
474
475 private:
476#if !_GLIBCXX_INLINE_VERSION
477 void
478 _M_write(const char_type* __s, streamsize __n)
479 { std::__ostream_insert(*this, __s, __n); }
480#endif
481
482#pragma GCC diagnostic push
483#pragma GCC diagnostic ignored "-Wc++17-extensions" // for if-constexpr
484 template<typename _To, typename _From>
485 static _To
486 _S_cast_flt(_From __f)
487 {
488 _To __d = static_cast<_To>(__f);
489 // _GLIBCXX_RESOLVE_LIB_DEFECTS
490 // 4101: LWG 117 loses the sign for negative NaN on some arches.
491#if defined __riscv
492 _To __sign;
493#if __cpp_constexpr && __has_builtin(__builtin_bit_cast)
494 if constexpr (sizeof(__f) == sizeof(short))
495 __sign = static_cast<_To>(__builtin_bit_cast(short, __f));
496 else if constexpr (sizeof(__f) == sizeof(int))
497 __sign = static_cast<_To>(__builtin_bit_cast(int, __f));
498 else if constexpr (sizeof(__f) == sizeof(long long))
499 __sign = static_cast<_To>(__builtin_bit_cast(long long, __f));
500 else
501#endif
502 __sign = __builtin_signbit(__f) ? _To(-1.0) : _To(+1.0);
503
504 if _GLIBCXX17_CONSTEXPR (__is_same(_To, double))
505 __d = __builtin_copysign(__d, __sign);
506 else if _GLIBCXX17_CONSTEXPR (__is_same(_To, long double))
507 __d = __builtin_copysignl(__d, __sign);
508#endif
509 return __d;
510 }
511 };
512#pragma GCC diagnostic pop
513
514 /**
515 * @brief Performs setup work for output streams.
516 *
517 * Objects of this class are created before all of the standard
518 * inserters are run. It is responsible for <em>exception-safe prefix and
519 * suffix operations</em>.
520 */
521 template <typename _CharT, typename _Traits>
522 class basic_ostream<_CharT, _Traits>::sentry
523 {
524 // Data Members.
525 bool _M_ok;
526 basic_ostream<_CharT, _Traits>& _M_os;
527
528 public:
529 /**
530 * @brief The constructor performs preparatory work.
531 * @param __os The output stream to guard.
532 *
533 * If the stream state is good (@a __os.good() is true), then if the
534 * stream is tied to another output stream, @c is.tie()->flush()
535 * is called to synchronize the output sequences.
536 *
537 * If the stream state is still good, then the sentry state becomes
538 * true (@a okay).
539 */
540 explicit
541 sentry(basic_ostream<_CharT, _Traits>& __os);
542
543#pragma GCC diagnostic push
544#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
545 /**
546 * @brief Possibly flushes the stream.
547 *
548 * If @c ios_base::unitbuf is set in @c os.flags(), and
549 * @c std::uncaught_exception() is true, the sentry destructor calls
550 * @c flush() on the output stream.
551 */
552 ~sentry()
553 {
554 // XXX MT
555 if (bool(_M_os.flags() & ios_base::unitbuf) && !uncaught_exception())
556 {
557 // Can't call flush directly or else will get into recursive lock.
558 if (_M_os.rdbuf() && _M_os.rdbuf()->pubsync() == -1)
559 _M_os.setstate(ios_base::badbit);
560 }
561 }
562#pragma GCC diagnostic pop
563
564 /**
565 * @brief Quick status checking.
566 * @return The sentry state.
567 *
568 * For ease of use, sentries may be converted to booleans. The
569 * return value is that of the sentry state (true == okay).
570 */
571#if __cplusplus >= 201103L
572 explicit
573#endif
574 operator bool() const
575 { return _M_ok; }
576 };
577
578 ///@{
579 /**
580 * @brief Character inserters
581 * @param __out An output stream.
582 * @param __c A character.
583 * @return out
584 *
585 * Behaves like one of the formatted arithmetic inserters described in
586 * std::basic_ostream. After constructing a sentry object with good
587 * status, this function inserts a single character and any required
588 * padding (as determined by [22.2.2.2.2]). @c __out.width(0) is then
589 * called.
590 *
591 * If @p __c is of type @c char and the character type of the stream is not
592 * @c char, the character is widened before insertion.
593 */
594 template<typename _CharT, typename _Traits>
595 inline basic_ostream<_CharT, _Traits>&
596 operator<<(basic_ostream<_CharT, _Traits>& __out, _CharT __c)
597 {
598 if (__out.width() != 0)
599 return __ostream_insert(__out, &__c, 1);
600 __out.put(__c);
601 return __out;
602 }
603
604 template<typename _CharT, typename _Traits>
605 inline basic_ostream<_CharT, _Traits>&
606 operator<<(basic_ostream<_CharT, _Traits>& __out, char __c)
607 { return (__out << __out.widen(__c)); }
608
609 // Specialization
610 template<typename _Traits>
611 inline basic_ostream<char, _Traits>&
612 operator<<(basic_ostream<char, _Traits>& __out, char __c)
613 {
614 if (__out.width() != 0)
615 return __ostream_insert(__out, &__c, 1);
616 __out.put(__c);
617 return __out;
618 }
619
620 // Signed and unsigned
621 template<typename _Traits>
622 inline basic_ostream<char, _Traits>&
623 operator<<(basic_ostream<char, _Traits>& __out, signed char __c)
624 { return (__out << static_cast<char>(__c)); }
625
626 template<typename _Traits>
627 inline basic_ostream<char, _Traits>&
628 operator<<(basic_ostream<char, _Traits>& __out, unsigned char __c)
629 { return (__out << static_cast<char>(__c)); }
630
631#if __cplusplus > 201703L
632 // The following deleted overloads prevent formatting character values as
633 // numeric values.
634
635 template<typename _Traits>
636 basic_ostream<char, _Traits>&
637 operator<<(basic_ostream<char, _Traits>&, wchar_t) = delete;
638
639#ifdef _GLIBCXX_USE_CHAR8_T
640 template<typename _Traits>
641 basic_ostream<char, _Traits>&
642 operator<<(basic_ostream<char, _Traits>&, char8_t) = delete;
643#endif
644
645 template<typename _Traits>
646 basic_ostream<char, _Traits>&
647 operator<<(basic_ostream<char, _Traits>&, char16_t) = delete;
648
649 template<typename _Traits>
650 basic_ostream<char, _Traits>&
651 operator<<(basic_ostream<char, _Traits>&, char32_t) = delete;
652
653#ifdef _GLIBCXX_USE_WCHAR_T
654#ifdef _GLIBCXX_USE_CHAR8_T
655 template<typename _Traits>
656 basic_ostream<wchar_t, _Traits>&
657 operator<<(basic_ostream<wchar_t, _Traits>&, char8_t) = delete;
658#endif // _GLIBCXX_USE_CHAR8_T
659
660 template<typename _Traits>
661 basic_ostream<wchar_t, _Traits>&
662 operator<<(basic_ostream<wchar_t, _Traits>&, char16_t) = delete;
663
664 template<typename _Traits>
665 basic_ostream<wchar_t, _Traits>&
666 operator<<(basic_ostream<wchar_t, _Traits>&, char32_t) = delete;
667#endif // _GLIBCXX_USE_WCHAR_T
668#endif // C++20
669 ///@}
670
671 ///@{
672 /**
673 * @brief String inserters
674 * @param __out An output stream.
675 * @param __s A character string.
676 * @return out
677 * @pre @p __s must be a non-NULL pointer
678 *
679 * Behaves like one of the formatted arithmetic inserters described in
680 * std::basic_ostream. After constructing a sentry object with good
681 * status, this function inserts @c traits::length(__s) characters starting
682 * at @p __s, widened if necessary, followed by any required padding (as
683 * determined by [22.2.2.2.2]). @c __out.width(0) is then called.
684 */
685 template<typename _CharT, typename _Traits>
686 inline basic_ostream<_CharT, _Traits>&
687 operator<<(basic_ostream<_CharT, _Traits>& __out, const _CharT* __s)
688 {
689 if (!__s)
690 __out.setstate(ios_base::badbit);
691 else
692 __ostream_insert(__out, __s,
693 static_cast<streamsize>(_Traits::length(__s)));
694 return __out;
695 }
696
697 template<typename _CharT, typename _Traits>
698 basic_ostream<_CharT, _Traits> &
699 operator<<(basic_ostream<_CharT, _Traits>& __out, const char* __s);
700
701 // Partial specializations
702 template<typename _Traits>
703 inline basic_ostream<char, _Traits>&
704 operator<<(basic_ostream<char, _Traits>& __out, const char* __s)
705 {
706 if (!__s)
707 __out.setstate(ios_base::badbit);
708 else
709 __ostream_insert(__out, __s,
710 static_cast<streamsize>(_Traits::length(__s)));
711 return __out;
712 }
713
714 // Signed and unsigned
715 template<typename _Traits>
716 inline basic_ostream<char, _Traits>&
717 operator<<(basic_ostream<char, _Traits>& __out, const signed char* __s)
718 { return (__out << reinterpret_cast<const char*>(__s)); }
719
720 template<typename _Traits>
721 inline basic_ostream<char, _Traits> &
722 operator<<(basic_ostream<char, _Traits>& __out, const unsigned char* __s)
723 { return (__out << reinterpret_cast<const char*>(__s)); }
724
725#if __cplusplus > 201703L
726 // The following deleted overloads prevent formatting strings as
727 // pointer values.
728
729 template<typename _Traits>
730 basic_ostream<char, _Traits>&
731 operator<<(basic_ostream<char, _Traits>&, const wchar_t*) = delete;
732
733#ifdef _GLIBCXX_USE_CHAR8_T
734 template<typename _Traits>
735 basic_ostream<char, _Traits>&
736 operator<<(basic_ostream<char, _Traits>&, const char8_t*) = delete;
737#endif // _GLIBCXX_USE_CHAR8_T
738
739 template<typename _Traits>
740 basic_ostream<char, _Traits>&
741 operator<<(basic_ostream<char, _Traits>&, const char16_t*) = delete;
742
743 template<typename _Traits>
744 basic_ostream<char, _Traits>&
745 operator<<(basic_ostream<char, _Traits>&, const char32_t*) = delete;
746
747#ifdef _GLIBCXX_USE_WCHAR_T
748#ifdef _GLIBCXX_USE_CHAR8_T
749 template<typename _Traits>
750 basic_ostream<wchar_t, _Traits>&
751 operator<<(basic_ostream<wchar_t, _Traits>&, const char8_t*) = delete;
752#endif
753
754 template<typename _Traits>
755 basic_ostream<wchar_t, _Traits>&
756 operator<<(basic_ostream<wchar_t, _Traits>&, const char16_t*) = delete;
757
758 template<typename _Traits>
759 basic_ostream<wchar_t, _Traits>&
760 operator<<(basic_ostream<wchar_t, _Traits>&, const char32_t*) = delete;
761#endif // _GLIBCXX_USE_WCHAR_T
762#endif // C++20
763 ///@}
764
765 // Standard basic_ostream manipulators
766
767 /**
768 * @brief Write a newline and flush the stream.
769 *
770 * This manipulator is often mistakenly used when a simple newline is
771 * desired, leading to poor buffering performance. See
772 * https://gcc.gnu.org/onlinedocs/libstdc++/manual/streambufs.html#io.streambuf.buffering
773 * for more on this subject.
774 */
775 template<typename _CharT, typename _Traits>
776 inline basic_ostream<_CharT, _Traits>&
777 endl(basic_ostream<_CharT, _Traits>& __os)
778 { return flush(__os.put(__os.widen('\n'))); }
779
780 /**
781 * @brief Write a null character into the output sequence.
782 *
783 * <em>Null character</em> is @c CharT() by definition. For CharT
784 * of @c char, this correctly writes the ASCII @c NUL character
785 * string terminator.
786 */
787 template<typename _CharT, typename _Traits>
788 inline basic_ostream<_CharT, _Traits>&
789 ends(basic_ostream<_CharT, _Traits>& __os)
790 { return __os.put(_CharT()); }
791
792 /**
793 * @brief Flushes the output stream.
794 *
795 * This manipulator simply calls the stream's @c flush() member function.
796 */
797 template<typename _CharT, typename _Traits>
798 inline basic_ostream<_CharT, _Traits>&
799 flush(basic_ostream<_CharT, _Traits>& __os)
800 { return __os.flush(); }
801
802#if __cplusplus >= 201103L
803 // C++11 27.7.3.9 Rvalue stream insertion [ostream.rvalue]
804 // _GLIBCXX_RESOLVE_LIB_DEFECTS
805 // 1203. More useful rvalue stream insertion
806
807#if __cpp_concepts >= 201907L && __glibcxx_type_trait_variable_templates
808 // Use concepts if possible because they're cheaper to evaluate.
809 template<typename _Tp>
810 concept __derived_from_ios_base = is_class_v<_Tp>
811 && (!is_same_v<_Tp, ios_base>)
812 && requires (_Tp* __t, ios_base* __b) { __b = __t; };
813
814 template<typename _Os, typename _Tp>
815 requires __derived_from_ios_base<_Os>
816 && requires (_Os& __os, const _Tp& __t) { __os << __t; }
817 using __rvalue_stream_insertion_t = _Os&&;
818#else
819 template<typename _Tp>
820 using _Require_derived_from_ios_base
821 = _Require<is_class<_Tp>, __not_<is_same<_Tp, ios_base>>,
822 is_convertible<typename add_pointer<_Tp>::type, ios_base*>>;
823
824 template<typename _Os, typename _Tp,
825 typename = _Require_derived_from_ios_base<_Os>,
826 typename
827 = decltype(std::declval<_Os&>() << std::declval<const _Tp&>())>
828 using __rvalue_stream_insertion_t = _Os&&;
829#endif
830
831 /**
832 * @brief Generic inserter for rvalue stream
833 * @param __os An input stream.
834 * @param __x A reference to the object being inserted.
835 * @return __os
836 *
837 * This is just a forwarding function to allow insertion to
838 * rvalue streams since they won't bind to the inserter functions
839 * that take an lvalue reference.
840 */
841 template<typename _Ostream, typename _Tp>
842 inline __rvalue_stream_insertion_t<_Ostream, _Tp>
843 operator<<(_Ostream&& __os, const _Tp& __x)
844 {
845 __os << __x;
846 return std::move(__os);
847 }
848
849#ifdef __glibcxx_syncbuf // C++ >= 20 && HOSTED && CXX11ABI
850 template<typename _CharT, typename _Traits>
851 class __syncbuf_base : public basic_streambuf<_CharT, _Traits>
852 {
853 public:
854 static bool*
855 _S_get(basic_streambuf<_CharT, _Traits>* __buf [[maybe_unused]]) noexcept
856 {
857#if __cpp_rtti
858 if (auto __p = dynamic_cast<__syncbuf_base*>(__buf))
859 return &__p->_M_emit_on_sync;
860#endif
861 return nullptr;
862 }
863
864 protected:
865 __syncbuf_base(basic_streambuf<_CharT, _Traits>* __w = nullptr)
866 : _M_wrapped(__w)
867 { }
868
869 basic_streambuf<_CharT, _Traits>* _M_wrapped = nullptr;
870 bool _M_emit_on_sync = false;
871 bool _M_needs_sync = false;
872 };
873
874 template<typename _CharT, typename _Traits>
875 inline basic_ostream<_CharT, _Traits>&
876 emit_on_flush(basic_ostream<_CharT, _Traits>& __os)
877 {
878 if (bool* __flag = __syncbuf_base<_CharT, _Traits>::_S_get(__os.rdbuf()))
879 *__flag = true;
880 return __os;
881 }
882
883 template<typename _CharT, typename _Traits>
884 inline basic_ostream<_CharT, _Traits>&
885 noemit_on_flush(basic_ostream<_CharT, _Traits>& __os)
886 {
887 if (bool* __flag = __syncbuf_base<_CharT, _Traits>::_S_get(__os.rdbuf()))
888 *__flag = false;
889 return __os;
890 }
891
892 template<typename _CharT, typename _Traits>
893 inline basic_ostream<_CharT, _Traits>&
894 flush_emit(basic_ostream<_CharT, _Traits>& __os)
895 {
896 struct _Restore
897 {
898 ~_Restore() { *_M_flag = _M_prev; }
899
900 bool _M_prev = false;
901 bool* _M_flag = &_M_prev;
902 } __restore;
903
904 if (bool* __flag = __syncbuf_base<_CharT, _Traits>::_S_get(__os.rdbuf()))
905 {
906 __restore._M_prev = *__flag;
907 __restore._M_flag = __flag;
908 *__flag = true;
909 }
910
911 __os.flush();
912 return __os;
913 }
914#endif // __glibcxx_syncbuf
915
916#if __cpp_lib_print // C++ >= 23
917
918 inline void
919 vprint_nonunicode(ostream& __os, string_view __fmt, format_args __args)
920 {
921 ostream::sentry __cerb(__os);
922 if (__cerb)
923 {
924 __format::_Str_sink<char> __buf;
925 std::vformat_to(__buf.out(), __os.getloc(), __fmt, __args);
926 auto __out = __buf.view();
927
928 __try
929 {
930 std::__ostream_write(__os, __out.data(), __out.size());
931 }
932 __catch(const __cxxabiv1::__forced_unwind&)
933 {
934 __os._M_setstate(ios_base::badbit);
935 __throw_exception_again;
936 }
937 __catch(...)
938 { __os._M_setstate(ios_base::badbit); }
939 }
940 }
941
942 inline void
943 vprint_unicode(ostream& __os, string_view __fmt, format_args __args)
944 {
945#if !defined(_WIN32) || defined(__CYGWIN__)
946 // For most targets we don't need to do anything special to write
947 // Unicode to a terminal.
948 std::vprint_nonunicode(__os, __fmt, __args);
949#else
950 ostream::sentry __cerb(__os);
951 if (__cerb)
952 {
953 __format::_Str_sink<char> __buf;
954 std::vformat_to(__buf.out(), __os.getloc(), __fmt, __args);
955 auto __out = __buf.view();
956
957 void* __open_terminal(streambuf*);
958 error_code __write_to_terminal(void*, span<char>);
959 // If stream refers to a terminal, write a Unicode string to it.
960 if (auto __term = __open_terminal(__os.rdbuf()))
961 {
962#if !defined(_WIN32) || defined(__CYGWIN__)
963 // For POSIX, __open_terminal(streambuf*) uses fdopen to open a
964 // new file, so we would need to close it here. This code is not
965 // actually compiled because it's inside an #ifdef _WIN32 group,
966 // but just in case that changes in future ...
967 struct _Guard
968 {
969 _Guard(void* __p) : _M_f((FILE*)__p) { }
970 ~_Guard() { std::fclose(_M_f); }
971 _Guard(_Guard&&) = delete;
972 _Guard& operator=(_Guard&&) = delete;
973 FILE* _M_f;
974 };
975 _Guard __g(__term);
976#endif
977
978 ios_base::iostate __err = ios_base::goodbit;
979 __try
980 {
981 if (__os.rdbuf()->pubsync() == -1)
982 __err = ios::badbit;
983 else if (auto __e = __write_to_terminal(__term, __out))
984 if (__e != std::make_error_code(errc::illegal_byte_sequence))
985 __err = ios::badbit;
986 }
987 __catch(const __cxxabiv1::__forced_unwind&)
988 {
989 __os._M_setstate(ios_base::badbit);
990 __throw_exception_again;
991 }
992 __catch(...)
993 { __os._M_setstate(ios_base::badbit); }
994
995 if (__err)
996 __os.setstate(__err);
997 return;
998 }
999
1000 // Otherwise just insert the string as vprint_nonunicode does.
1001 __try
1002 {
1003 std::__ostream_write(__os, __out.data(), __out.size());
1004 }
1005 __catch(const __cxxabiv1::__forced_unwind&)
1006 {
1007 __os._M_setstate(ios_base::badbit);
1008 __throw_exception_again;
1009 }
1010 __catch(...)
1011 { __os._M_setstate(ios_base::badbit); }
1012 }
1013#endif // _WIN32
1014 }
1015
1016 template<typename... _Args>
1017 inline void
1018 print(ostream& __os, format_string<_Args...> __fmt, _Args&&... __args)
1019 {
1020 auto __fmtargs = std::make_format_args(__args...);
1021 if constexpr (__unicode::__literal_encoding_is_utf8())
1022 std::vprint_unicode(__os, __fmt.get(), __fmtargs);
1023 else
1024 std::vprint_nonunicode(__os, __fmt.get(), __fmtargs);
1025 }
1026
1027 template<typename... _Args>
1028 inline void
1029 println(ostream& __os, format_string<_Args...> __fmt, _Args&&... __args)
1030 {
1031 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1032 // 4088. println ignores the locale imbued in std::ostream
1033 std::print(__os, "{}\n", std::format(__os.getloc(), __fmt,
1034 std::forward<_Args>(__args)...));
1035 }
1036
1037 // Defined for C++26, supported as an extension to C++23.
1038 inline void println(ostream& __os)
1039 {
1040#if defined(_WIN32) && !defined(__CYGWIN__)
1041 if constexpr (__unicode::__literal_encoding_is_utf8())
1042 std::vprint_unicode(__os, "\n", std::make_format_args());
1043 else
1044#endif
1045 __os.put('\n');
1046 }
1047
1048#endif // __cpp_lib_print
1049
1050#endif // C++11
1051
1052_GLIBCXX_END_NAMESPACE_VERSION
1053} // namespace std
1054
1055#include <bits/ostream.tcc>
1056
1057#endif /* _GLIBCXX_OSTREAM */