Preferred Method for Expressing Template Negative Numeric Literals

Although there is a question of a good way to use wildcard numeric literals, he does not mention the case where the numeric literal is a negative value.

Which option should be preferred and why?

A

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

IN

template <typename T>
T expr(T x)
{
    constexpr T scale = -T(9.0);
    return x * scale;
}
+4
source share
2 answers

Assuming you are only talking about arithmetic types (otherwise operator-you can overload to do something weird) ...

, (. ), A . , A.

A , B , ,

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

, 32768 , (short)-32768, (short)32768.

+4

A B.

A , B, , - (, .., ). .

, , .

+6

Source: https://habr.com/ru/post/1611831/


All Articles