Это также работает с MSVC, GCC и Clang на моем ПК. Тем не менее, GCC делает странные вещи на нашем CI. < /P>
Код превращается в обнаженные предметы первой необходимости: < /p>
Код: Выделить всё
#include
#include
#include
template
TargetType convert(SourceType value)
{
if constexpr (std::is_integral_v && std::is_floating_point_v)
{
// Double only has a precision of (53 bits mantissa), some platforms have long double, so we can represent all values accurately.
using DoubleType = std::conditional_t std::numeric_limits::digits),
long double,
double>;
// Conversion from integer to double/float: Fit all values into the range [0;1].
DoubleType result = 0.0;
if constexpr (std::is_signed_v)
{
// Solutions looks more complex, because the behavior differs between compilers: MSVC may rely on
// implementation-defined behavior for signed overflows, while Clang/GCC applies wraparound semantics
// when converting negative values to unsigned types.
using Unsigned = std::make_unsigned_t;
constexpr auto min = std::numeric_limits::min();
constexpr auto max = std::numeric_limits::max();
const Unsigned shifted = static_cast(static_cast(value) - static_cast(min));
result = static_cast(shifted) / static_cast(max);
std::cout
Подробнее здесь: [url]https://stackoverflow.com/questions/79766349/normalize-signed-integer-values-to-range-0-0-1-0[/url]
Мобильная версия