Proposal: overload conflict resolution
Chris Miller
chris at dprogramming.com
Sun Dec 10 06:36:51 PST 2006
Given the following function prototypes:
void foo(char[] s);
void foo(wchar[] s);
void foo(dchar[] s);
Currently, if you try to do foo("hello"), the compiler will complain
because string literals simulteneous match all the above types.
Proposal:
void foo(default char[] s);
void foo(wchar[] s);
void foo(dchar[] s);
foo("hello") will now select the char[] version because it was marked as
the default type in the overload.
What it does not do:
1) Resolve conflicts between different scopes.
2) Override exact matches.
The way overloads work now is helpful in some cases, but in other cases,
it's perfectly fine to prefer an overload over another.
Example where you do not want a default overload: working with binary,
e.g. writing to Stream or Socket, where the wrong type can screw up the
format or transmission.
Example where you do: custom string object's constructor that wants to
allow char[], wchar[] and dchar[] types, but wants to default string
literals to char[].
The compiler would go down the line of parameters of overloads, and upon
any conflicts, would look for default to resolve them. If default is used
to resolve conflicts in more that one of the functions, it's an actual
conflict.
Strange example:
void bar(default char[] s, int x);
void bar(char[] s, default long x);
Note: this example probably wouldn't actually be used; as with most
language constructs, there's a way to abuse it, but this example gets a
point across that it at least has logic:
bar("hello", 42) chooses the first one because the string literal
conflicted and went with the default one.
bar("hello"c, 42) chooses the second one; the string literal specified
char[] (with the c) and then had a conflict with the second parameter,
where default resolved it.
The programmer knows which overloads, if any, can be preferred over
others, because this feature works only confined within one scope, and so
it is safe to let him choose for you.
Where this can be useful:
1) String literals conflicting with char[], wchar[] and dchar[].
2) null conflicting with string types, delegates, pointers, and class
references.
3) Integer literals conflicting with the number types.
4) Different levels of derived classes conflicting with each other.
Thanks,
- Chris
More information about the Digitalmars-d
mailing list