|
| 1 | +#ifndef DICE_TEMPLATELIBRARY_FORMAT_TO_OSTREAM |
| 2 | +#define DICE_TEMPLATELIBRARY_FORMAT_TO_OSTREAM |
| 3 | + |
| 4 | +/*! |
| 5 | + * Note: This file does not use concepts/requires anywhere because their evaluation |
| 6 | + * causes an infinite loop (compiler error: "evaluation of constraint depends on itself"). |
| 7 | + * |
| 8 | + * Old-school SFINAE does not have this issue. |
| 9 | + */ |
| 10 | + |
| 11 | +#include <format> |
| 12 | +#include <iterator> |
| 13 | +#include <ostream> |
| 14 | +#include <string> |
| 15 | +#include <type_traits> |
| 16 | + |
| 17 | +namespace dice::template_library { |
| 18 | + |
| 19 | + /** |
| 20 | + * Detect if a type can be used with operator<< of an ostream. |
| 21 | + * |
| 22 | + * @tparam T type to check |
| 23 | + * @tparam Char char-type of the ostream |
| 24 | + * @tparam CharTraits char-traits-type of the ostream |
| 25 | + */ |
| 26 | + template<typename T, typename Char, typename CharTraits, typename = void> |
| 27 | + struct is_ostreamable : std::false_type { |
| 28 | + }; |
| 29 | + |
| 30 | + template<typename T, typename Char, typename CharTraits> |
| 31 | + struct is_ostreamable<T, Char, CharTraits, std::void_t<decltype(std::declval<std::basic_ostream<Char, CharTraits> &>() << std::declval<T const &>())>> : std::true_type { |
| 32 | + }; |
| 33 | + |
| 34 | + template<typename T, typename Char, typename CharTraits> |
| 35 | + inline constexpr bool is_ostreamable_v = is_ostreamable<T, Char, CharTraits>::value; |
| 36 | + |
| 37 | +} // namespace dice::template_library |
| 38 | + |
| 39 | +/** |
| 40 | + * An overload for ostream operator<< for any type that is formattable with std::format |
| 41 | + * |
| 42 | + * @tparam Char char-type of the ostream and the formatter |
| 43 | + * @tparam CharTraits char-traits-type of the ostream |
| 44 | + * @param stream ostream |
| 45 | + * @param value value to stream via std::formatter implementation |
| 46 | + * @return stream |
| 47 | + */ |
| 48 | +template<typename T, typename Char = char, typename CharTraits = std::char_traits<char>, typename = std::enable_if_t<std::formattable<T, Char> && !dice::template_library::is_ostreamable_v<T, Char, CharTraits>>> |
| 49 | +std::basic_ostream<Char, CharTraits> &operator<<(std::basic_ostream<Char, CharTraits> &stream, T const &value) { |
| 50 | + std::format_to(std::ostreambuf_iterator<Char, CharTraits>{stream}, "{}", value); |
| 51 | + return stream; |
| 52 | +} |
| 53 | + |
| 54 | +#endif // DICE_TEMPLATELIBRARY_FORMAT_TO_OSTREAM |
0 commit comments