Why does this template not have the desired result?

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Jul 19 13:48:39 PDT 2013


On Fri, Jul 19, 2013 at 10:42:54PM +0200, Adam D. Ruppe wrote:
> On Friday, 19 July 2013 at 20:26:36 UTC, Gary Willoughby wrote:
> >Why does this template not have the desired result? I honestly
> >though it would return true.
> 
> It is because size_t is an unsigned type. Comparisons between signed
> and unsigned numbers can be surprising because if either of the
> items being compared are unsigned, the whole comparison is unsigned.
> 
> Negative signed numbers, when interpreted as unsigned, become very
> large numbers because the bits are flipped when you go negative.
> cast(ubyte) -1 == 255, and of course, 255 <= 10 is false.
[...]

Yikes.

I would've expected a compiler warning (at least!) for this, or an
outright compile error, unless you use an explicit cast. This kind of
silent conversion is just asking for bugs (and newbie annoyance when
they can't figure out what went wrong).


> The way I'd do the inBounds is to just use T size instead of size_t
> size.

Yeah, comparing disparate types is tricky business, and not recommended
if it can be avoided.


> template inBounds(T, T size) { snip same stuff }
> 
> then
>         writefln("%s", inBounds!(int, 10).result); // true as
> expected


T

-- 
Just because you can, doesn't mean you should.


More information about the Digitalmars-d-learn mailing list