Why is int implicitly convertible to ulong?
Jonathan M Davis
jmdavisProg at gmx.com
Fri Feb 21 05:30:28 PST 2014
On Friday, February 21, 2014 12:41:07 Hannes Steffenhagen wrote:
> The specific problem here was when working with std.json.
>
> std.json distinguishes between UINTEGER and INTEGER, so I had
> code like
>
> static if(is(T : ulong)) {
> // must be UINTEGER
> } else static if(is(T : long)) {
> // can be either INTEGER or UINTEGER
> }
>
>
> I've since found out about isSigned and isUnsigned, still it was
> mighty confusing for me that the first case was selected for
> signed types.
Well, it is using : - which means implicit conversion, which is always
something that you should be careful with in generic code. Technically,
something like
struct S
{
ulong ul;
alias ul this;
}
would match it as well, and depending on what the code inside the static if is
like, it might work, but there's also a good chance that it wouldn't. Using
is(T == ulong) if you want to require that it be exactly ulong, or
isUnsigned!T if you want any unsigned integral type. Using implicit conversion
in generic code _can_ be useful, but you need to be _very_ careful with it.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list