Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preferred way of expressing templated negative numeric literals

Although there is a good question about the usage of templated numeric literals, it doesn't mention the case when the numeric literal is a negative value.

Which variant should be preferred and why?

A

template <typename T>
T expr(T x)
{
    constexpr T scale = T(-9.0);
    return x * scale;
}

B

template <typename T>
T expr(T x)
{
    constexpr T scale = -T(9.0);
    return x * scale;
}
like image 721
plasmacel Avatar asked Dec 24 '22 13:12

plasmacel


1 Answers

I would favor A over B.

Option A assumes less about the type than B in that the unary - may not be well defined for all types (such as overflow conditions etc. but it is fine for the numeric literal). That and it is a little easier on the eyes.

Sure, the question is for numerical types, so either should be just fine.

like image 140
Niall Avatar answered Jan 04 '23 23:01

Niall