I am currently writing some glsl like vector math classes in C++, and I just implemented an abs()
function like this:
template
static
Since they are the implementation, they are free to make as many assumptions as they want. They know the format of the double
and can play tricks with that instead.
Likely (as in almost not even a question), your double
is the binary64 format. This means the sign has it's own bit, and an absolute value is merely clearing that bit. For example, as a specialization, a compiler implementer may do the following:
template <>
double abs(const double x)
{
// breaks strict aliasing, but compiler writer knows this behavior for the platform
uint64_t i = reinterpret_cast(x);
i &= 0x7FFFFFFFFFFFFFFFULL; // clear sign bit
return reinterpret_cast(i);
}
This removes branching and may run faster.