Skip to content

Instantly share code, notes, and snippets.

@haxpor
Last active September 2, 2019 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haxpor/a3ed3172ffc780b0c923091726d0eb94 to your computer and use it in GitHub Desktop.
Save haxpor/a3ed3172ffc780b0c923091726d0eb94 to your computer and use it in GitHub Desktop.
non-member function overloading an operator. Example defined in ostream to work with primitive normal types, which be idea to expand for user-defined object to output it into output stream. Excerpted from ostream header. See https://www.quora.com/What-are-the-differences-between-a-member-operator-function-and-a-friend-operator-function.
//@{
/**
* @brief String inserters
* @param __out An output stream.
* @param __s A character string.
* @return out
* @pre @p __s must be a non-NULL pointer
*
* Behaves like one of the formatted arithmetic inserters described in
* std::basic_ostream. After constructing a sentry object with good
* status, this function inserts @c traits::length(__s) characters starting
* at @p __s, widened if necessary, followed by any required padding (as
* determined by [22.2.2.2.2]). @c __out.width(0) is then called.
*/
template<typename _CharT, typename _Traits>
inline basic_ostream<_CharT, _Traits>&
operator<<(basic_ostream<_CharT, _Traits>& __out, const _CharT* __s)
{
if (!__s)
__out.setstate(ios_base::badbit);
else
__ostream_insert(__out, __s,
static_cast<streamsize>(_Traits::length(__s)));
return __out;
}
template<typename _CharT, typename _Traits>
basic_ostream<_CharT, _Traits> &
operator<<(basic_ostream<_CharT, _Traits>& __out, const char* __s);
// Partial specializations
template<class _Traits>
inline basic_ostream<char, _Traits>&
operator<<(basic_ostream<char, _Traits>& __out, const char* __s)
{
if (!__s)
__out.setstate(ios_base::badbit);
else
__ostream_insert(__out, __s,
static_cast<streamsize>(_Traits::length(__s)));
return __out;
}
// Signed and unsigned
template<class _Traits>
inline basic_ostream<char, _Traits>&
operator<<(basic_ostream<char, _Traits>& __out, const signed char* __s)
{ return (__out << reinterpret_cast<const char*>(__s)); }
template<class _Traits>
inline basic_ostream<char, _Traits> &
operator<<(basic_ostream<char, _Traits>& __out, const unsigned char* __s)
{ return (__out << reinterpret_cast<const char*>(__s)); }
//@}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment