Why is C++20's `std::popcount` restricted to unsigned types?
The functions from P0553R4: Bit operations are constrained to only work on unsigned integers. The proposal does not give a reason for this constraint. I can see that this makes sense if the bit representation of a signed integer is not defined, but with C++20, we are guaranteed that signed integers use two's complement.
To me, it thus seems reasonable to allow e.g. std::popcount
to be called with a signed integer type, as an implementation could simply cast to the corresponding unsigned type to do the bit-operation in the unsigned domain.
What is the reason for P0553R4 to add this constraint? (Is it simply missing synchronization between P0553R4 and P0907R4?)
---------------------------------------------------------------------------------------------------------------
Pretty simple: Implicit widening conversions on unsigned types do not change the result. Implicit widening conversions on signed types (including promotions) perform sign-extension, which does change the result if the input was negative.
Having an operation whose result becomes incorrect due to integer promotion definitely falls into the "foot cannon" category.
You can still feed (bit patterns representing) negative values to popcount
, but you have to take control of the conversion sequence, which helps you get the result you expect.
0 Comments
If you have any doubts, Please let me know