If I understand well, is it guaranteed that :
static_cast<std::int8_t>(static_cast<std::int16_t>(-3)) == -3
?
Because -3 can be represented in an std::int8_t.
Thus in the example of a two s complement:
Then in the example of the two's complement function, do I need an intermediaite cast to std::uintmax_t?
#include <type_traits>
template <typename T>
T twos_complement(T val)
{
typedef std::make_unsigned<T>::type U;
return static_cast<T>(-static_cast<uintmax_t>(static_cast<U>(val)));
}
because
return static_cast<T>(-static_cast<U>(val));
integral promotion applied before unary minus could "ruin the effect of casting to an unsigned type if T is narrower than int"?