// Copyright 2023 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_STRINGS_TO_STRING_H_ #define BASE_STRINGS_TO_STRING_H_ #include #include #include #include #include #include "base/template_util.h" #include "base/types/supports_ostream_operator.h" namespace base { namespace internal { // I/O manipulators are function pointers, but should be sent directly to the // `ostream` instead of being cast to `const void*` like other function // pointers. template constexpr bool IsIomanip = false; template constexpr bool IsIomanip>> = true; // Function pointers implicitly convert to `bool`, so use this to avoid printing // function pointers as 1 or 0. template constexpr bool WillBeIncorrectlyStreamedAsBool = false; template constexpr bool WillBeIncorrectlyStreamedAsBool< T, std::enable_if_t> && !IsIomanip>>> = true; // Fallback case when there is no better representation. template struct ToStringHelper { static void Stringify(const T& v, std::ostringstream& ss) { ss << "[" << sizeof(v) << "-byte object at 0x" << std::addressof(v) << "]"; } }; // Most streamables. template struct ToStringHelper< T, std::enable_if_t::value && !WillBeIncorrectlyStreamedAsBool>> { static void Stringify(const T& v, std::ostringstream& ss) { ss << v; } }; // Functions and function pointers. template struct ToStringHelper< T, std::enable_if_t::value && WillBeIncorrectlyStreamedAsBool>> { static void Stringify(const T& v, std::ostringstream& ss) { ToStringHelper::Stringify(reinterpret_cast(v), ss); } }; // Non-streamables that have a `ToString` member. template struct ToStringHelper< T, std::enable_if_t::value && SupportsToString::value>> { static void Stringify(const T& v, std::ostringstream& ss) { // .ToString() may not return a std::string, e.g. blink::WTF::String. ToStringHelper::Stringify(v.ToString(), ss); } }; // Non-streamable enums (i.e. scoped enums where no `operator<<` overload was // declared). template struct ToStringHelper< T, std::enable_if_t::value && std::is_enum_v>> { static void Stringify(const T& v, std::ostringstream& ss) { using UT = typename std::underlying_type_t; ToStringHelper::Stringify(static_cast(v), ss); } }; } // namespace internal // Converts any type to a string, preferring defined operator<<() or ToString() // methods if they exist. template std::string ToString(const Ts&... values) { std::ostringstream ss; (internal::ToStringHelper>::Stringify(values, ss), ...); return ss.str(); } } // namespace base #endif // BASE_STRINGS_TO_STRING_H_