Reputation: 43179
In C++11, what is the advantage of std::numeric_limits<Type>::max_digits10
returning 0 for a Type
that is a reference to floating point number?
For example:
constexpr int precisionPositive(const float &floatVal)
{
using numericType = std::remove_reference<decltype(floatVal)>::type;
constexpr int digits = std::numeric_limits<numericType>::max_digits10;
return digits;
}
constexpr int precisionZero(const float &floatVal)
{
using numericType = decltype(floatVal);
constexpr int digits = std::numeric_limits<numericType>::max_digits10;
return digits;
}
The precisionPositive
returns 9 and precisionZero
returns 0.
Under what circumstances would the zero value helpful, as opposed to giving a compile time error?
Upvotes: 3
Views: 213
Reputation: 4251
I don't have a proper answer for the question "why". Buy I might use this code:
C++11:
template<typename T>
using bare_value_t=typename
std::decay<T>::type;
C++14:
template<typename T>
using bare_value_t=
std::decay_t<T>;
C++20:
template<typename T>
using bare_value_t=
std::remove_cvref_t<T>;
And:
template<typename T>
using limits=
std::numeric_limits<bare_value_t<T> >;
cout<<limits<float&>::max_digits10;
Upvotes: 0
Reputation: 26800
As per the C++ standard (n4659), in the numeric_limits
class template the default value for max_digits10
is 0
.
21.3.4 Class template numeric_limits [numeric.limits]
namespace std { template<class T> class numeric_limits { public: ... static constexpr int max_digits10 = 0;
And it is only when the template is specialized for float
, double
etc, max_digits10
is given a particular value.
Consider the specialization for float
.
21.3.4.2 numeric_limits specializations [numeric.special]
namespace std { template<> class numeric_limits<float> { public: ... static constexpr int max_digits10 = 9;
The implementations also follow this. See GCC's Standard C++ Library header limits for example.
So, except for specializations where max_digits10
is given a particular value, the default value is 0
and therefore the value of max_digits10
for references to floating point types is also 0
.
Upvotes: 2