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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With