CppCoreGuidelines icon indicating copy to clipboard operation
CppCoreGuidelines copied to clipboard

not_negative<T> for integer types?

Open istolboff opened this issue 10 years ago • 3 comments

There is a not_null template for pointers that cannot be null. Wouldn't it be beneficial to have not_negative template for integers that cannot be negative?

For example, gsl::span.size() returns the value of type size_type (which is std::ptrdiff_t). Is it really possible that size() of any span could be negative? And if not -- wouldn't it be nice to explicitly state this fact in the code? (It's not recommended to use unsigned integer types for this puprose)

Apart from self-documenting, we would get consistent 'non-negativeness' checking at run-time, for instance when passing integers as arguments for parameters of not_negative<> types.

istolboff avatar May 24 '16 11:05 istolboff

How is that different from unsigned? That said, I'd be happy to see a positive {int|float} so that square root, multiplication of equations, division, list size for accumulation, etc. wouldn't need to check.

lorros avatar Jun 24 '16 13:06 lorros

If I understand this correctly, signed integers are used for span’s index and size types because...

  1. When signed and unsigned types are mixed in arithmetic, the signed will get automatically “promoted” to unsigned with unexpected results leading to latent bugs.
  2. Since the standard defines overflow rules for unsigned but not for signed, using unsigned for indices can result in slower code than signed.

A gsl::not_negative would avoid those problems with unsigned ints but still enforce the not_negative invariant.

fisherro avatar Oct 14 '16 05:10 fisherro

"Not null" and "not negative" are not similar. If there was something done here, I think it would be more a special case of constrained value types -- just as we might want "an integer that is not negative (whose values is between 0 and (say) 32767)" we might want "an integer whose value is between 10 and 32."

Bit manipulation should use byte[sizeof(int)] or similar.

hsutter avatar Apr 10 '17 18:04 hsutter