You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The code is already smart enough to parse "123.0" as floating-point type.
The problem is that this does not round-trip, as the value serializes as "123", so now it is indistinguishable from pure-integer, and the floating-point-ness information is lost.
Proposed implementation for serializing numeric values below.
// Convert floating-point type to string in POSIX locale.// If result is composed entirely of digits or minus-sign,// append ".0" to preserve the type information.template<typename T>
static std::string as_str(const T x, /*is_integral=*/std::false_type)
{
staticthread_local std::unique_ptr<std::stringstream> sstr;
// reusing sstr per-thread as construction of stringstream// and ::imbue are both expensive.if(!sstr) {
sstr.reset(new std::stringstream);
sstr->imbue(std::locale::classic());
}
sstr->precision(std::numeric_limits<T>::digits10);
*sstr << x;
std::string s = sstr->str();
sstr->str(std::string()); // clear the dataif(s.find_first_not_of("0123456789-") == std::string::npos) {
s += ".0";
}
return s;
};
// Convert any integral type to base-10 representation,// using POSIX locale (no grouping characters are used).//// This is simple-enough so we can bypass using// the posix-locale-imbued stream and do it "manually"template<typename T>
static std::string as_str(T x, /*is_integral=*/std::true_type)
{
std::string s;
constbool is_neg = x < 0;
while(x) {
s.push_back('0' + abs(x % 10));
x /= 10;
}
if(s.empty()) {
s.push_back('0');
}
if(is_neg) {
s.push_back('-');
}
reverse(s.begin(), s.end());
return s;
}
// Dispatcher to as_str variants dealing with integral vs floating-point typestemplate<typename T, typename = typename std::enable_if<std::is_arithmetic<T>::value>::type >
static std::string as_str(const T x)
{
returnas_str(x, std::is_integral<T>());
}
The text was updated successfully, but these errors were encountered:
The code is already smart enough to parse "123.0" as floating-point type.
The problem is that this does not round-trip, as the value serializes as "123", so now it is indistinguishable from pure-integer, and the floating-point-ness information is lost.
Proposed implementation for serializing numeric values below.
The text was updated successfully, but these errors were encountered: