[Code] Fix build with older C++ libraries (#4549)

This adds a compile time concept to determine if from_chars has
floating-point support and uses fallbacks if not.

This is a C++17 feature but support for floats was only added to
libstdc++ with GCC 11.1 and LLVM libc++ in 20.0 (unreleased).
This commit is contained in:
hg 2024-11-24 18:18:36 -05:00 committed by GitHub
parent 7a841c11c5
commit 12ada57ee8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -414,6 +414,12 @@ static uint64_t MakeBits(std::span<const uint8_t> data)
return bits;
}
template <typename T>
concept has_from_chars = requires (const char* first, const char* last, T value)
{
std::from_chars(first, last, value);
};
template <typename T>
static T FromString(std::string_view sv)
{
@ -422,6 +428,14 @@ static T FromString(std::string_view sv)
// return false for empty (zero-length) strings
return !sv.empty();
}
else if constexpr (std::is_same_v<T, float> && !has_from_chars<T>)
{
return std::strtof(std::string(sv).c_str(), nullptr);
}
else if constexpr (std::is_same_v<T, double> && !has_from_chars<T>)
{
return std::strtod(std::string(sv).c_str(), nullptr);
}
else
{
// non numbers return a zero initialized T (could return nullopt instead)