| 94 | |
| 95 | template <typename T> |
| 96 | auto to_string(const T& num, const std::string def = "0") -> std::string { |
| 97 | // This is used to replace `std::to_string` as a locale independent |
| 98 | // number conversion using `std::to_chars`. |
| 99 | // An additional string parameter could be eventually provided with a |
| 100 | // default value to return in case the conversion fails. |
| 101 | |
| 102 | // Max buffer length: |
| 103 | // number of base-10 digits that can be represented by the type T without change + |
| 104 | // number of base-10 digits that are necessary to uniquely represent all distinct |
| 105 | // values of the type T (meaningful only for real numbers) + |
| 106 | // room for other characters such as "+-e,." |
| 107 | const size_t max = std::numeric_limits<T>::digits10 + std::numeric_limits<T>::max_digits10 + 10U; |
| 108 | |
| 109 | std::array<char, max> buffer; |
| 110 | |
| 111 | const auto p_init = buffer.data(); |
| 112 | |
| 113 | const auto result = std::to_chars(p_init, p_init + max, num); |
| 114 | |
| 115 | return (result.ec == std::errc()) ? std::string(p_init, result.ptr - p_init) : def; |
| 116 | } |
| 117 | |
| 118 | |
| 119 | } // namespace util |
no test coverage detected