Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no std::copysign specialization for integers in c++?

Tags:

c++

I tried using std::copysign to set an int with the sign of another.

int translate = getTranslate();
int offset = getOffset();
translate = std::copysign(offset, translate)

But copysign<int, int> returns a double. How should I use it better? Or what should I use instead?

like image 721
The Shmoo Avatar asked Oct 21 '19 09:10

The Shmoo


1 Answers

At first I was a bit confused about what std::copysign is actually good for, but the note on cppreference gives a reasonable motivation:

std::copysign is the only portable way to manipulate the sign of a NaN value (to examine the sign of a NaN, signbit may also be used)

Take this plus the fact that integers cannot be NaN and it makes sense that there is no std::copysign for int. On the other hand, a std::copysign<int,int> returning an int would come in handy in generic code, where you want it to work for double as well as for int. For this I would perhaps write my own wrapper, starting from a

template <typename T> 
T my_copy_sign(const T& t, const T& s);

and then specialize it accordingly.

PS: If you are only working on int, you probably dont need std::copysign in the first place.

like image 108
463035818_is_not_a_number Avatar answered Oct 24 '22 04:10

463035818_is_not_a_number