units
units copied to clipboard
Compiler error when UNIT_LIB_DEFAULT_TYPE is changed to float
When I changed the UNIT_LIB_DEFAULT_TYPE
to float
, my compiler (gcc-arm) spits out a very long error basically boiling down to:
units/include/units.h:1452:28: error: '(6.022141e+23f * 6.022141e+23f)' is not a constant expression
return y == 0 ? 1.0 : x * pow(x, y - 1);
~~^~~~~~~~~~~~~~~
It took a long time to realize the reason: (6.022141e+23f * 6.022141e+23f) is of the order of 10^46, which doesn't fit in a single-recision float whose max value is around 10^38.
A little more debugging later turns out the derivation of Stefan-Boltzmann constant around line 3954:
static constexpr const unit_t<compound_unit<power::watts, inverse<area::square_meters>, inverse<squared<squared<temperature::kelvin>>>>>
sigma((2 * math::cpow<5>(pi) * math::cpow<4>(R)) / (15 * math::cpow<3>(h) * math::cpow<2>(c) * math::cpow<4>(N_A))); ///< Stefan-Boltzmann constant.
contains Avogadro's number raised to 4th power.
I replaced this with pre-calculated constant, and the error disappeared:
static constexpr const unit_t<compound_unit<power::watts, inverse<area::square_meters>, inverse<squared<squared<temperature::kelvin>>>>>
sigma(5.670367e-8);///< Stefan-Boltzmann constant.
Personally I find this bug quite annoying. It is still present and prevents using the library correctly (without patching) with UNIT_LIB_DEFAULT_TYPE float. I would suggest to re-visit the "wontfix" decision for it and replace Stefan-Boltzmann (sigma) constant with a fixed numerical value, rather then compile-time computing it from others.
I'd marked this wontfix because the issue is solved generically in the still-unreleased version 3, which I'd hoped to have released about a month ago. In v3 we support templated underlying types and mixing/matching them properly, so the UNIT_LIB_DEFAULT_TYPE
isn't needed by users.
In general I want to be pedantic about not approximating units or constants, but you've convinced me in this case.
v3 also leaves C++14 users behind. I would like to see better support for float
in v2.
I wouldn't mind making v3 work with C++14.
I've placed #220 pull reqest that addreses this issue, so feel free to have a look if this simple change is in line with your intention to next v2 release