DIP 1015--Deprecation of Implicit Conversion of Int. & Char. Literals to bool--Formal Assement
Steven Schveighoffer
schveiguy at gmail.com
Tue Nov 13 14:46:17 UTC 2018
On 11/12/18 4:38 PM, Walter Bright wrote:
> On 11/12/2018 8:28 AM, 12345swordy wrote:
>> The issue that I see is unintended implicit conversation when passing
>> values to functions that have both int and bool overloads.
>
> The exact same thing happens when there are both int and short overloads.
>
> The underlying issue is is bool a one bit integer type, or something
> special? D defines it as a one bit integer type, fitting it into the
> other integer types using exactly the same rules.
D's definition is wanting. Most integer types act differently than bool:
1. Integer types can be incremented, bool cannot
2. Integer types truncate by removing the extraneous bits, bool
truncates to `true` for all values except 0.
3. Integer types have signed and unsigned variants, bool does not.
4. Integer types allow negation, bool does not.
5. Integer types can be used in a foreach(x; v1 .. v2), bool cannot.
It is true that bools act similarly to a 1-bit integer type in many
cases, but only via promotion. That is, they *convert* to 1-bit
integers, but don't behave like integers in their own type.
Regarding enums with base types, I admit I would totally expect an enum
based on int to match an int overload over a short overload.
You don't think this is confusing to an average developer?
import std.stdio;
void foo(int x)
{
writeln("integer");
}
void foo(short x)
{
writeln("short");
}
enum A : int
{
a = 1,
b = 2,
c = 3
}
void main()
{
auto a = A.a;
foo(A.a); // case 1
foo(a); // case 2
}
case 1 prints short, but case 2 prints integer. Both are passed the same
value. This comes into play when using compile-time generation -- you
are expecting the same behavior when using the same values. This is
super-confusing.
But on the other hand, an A can ONLY be 3 or less, so why doesn't case 2
print short? If VRP is used here, it seems lacking.
Maybe the biggest gripe here is that enums don't prefer their base types
over what their base types convert to. In the developer's mind, the
conversion is:
A => int => (via VRP) short
which seems more complex than just
A => int
> If it is to be a special type with special rules, what about the other
> integer types? D has a lot of basic types :-)
The added value of having bool implicitly cast to integer types is
great. I wouldn't want to eliminate that. The other way around seems of
almost no value, except maybe to avoid extra code in the compiler.
So, I would be fine to have bool be a non-integer type that implicitly
casts to integer for use in math or other reasons. But having 1 or 0
implicitly cast to true or false has little value, and especially using
it as "just another 1-bit integer", which it really isn't, has almost no
usage.
-Steve
More information about the Digitalmars-d-announce
mailing list