plasmacel
plasmacel

Reputation: 8540

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;
}

Upvotes: 4

Views: 143

Answers (2)

Niall
Niall

Reputation: 30605

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.

Upvotes: 6

Jonathan Wakely
Jonathan Wakely

Reputation: 171303

Assuming you're only talking about arithmetic types (otherwise operator- could be overloaded to do something weird) ...

They produce the same result for all arithmetic types except at the most negative value (see below), but A is more conventional and less likely to confuse people. That alone is enough reason for me to prefer A.

A can be used for the entire range of values of the type, but B cannot e.g.

short a = short(-32768);
assert( a == -32768 );
short b = -short(32768);
assert( b == -32768 );  // FAIL!

This is because 32768 is not a valid value for short, so there is no way to produce the value (short)-32768 by negating (short)32768.

Upvotes: 4

Related Questions