Accessing types by context

Lodovico Giaretta via Digitalmars-d digitalmars-d at puremagic.com
Wed Jun 29 04:45:18 PDT 2016


On Wednesday, 29 June 2016 at 10:51:39 UTC, qznc wrote:
> On Wednesday, 29 June 2016 at 03:11:52 UTC, Hiemlick Hiemlicker 
> wrote:
>> Suppose one has void test(myEnum e)
>>
>> enum myEnum
>> {
>> A,B,C
>> }
>>
>> It would be very cool if we could do
>>
>> test(A) instead of test(myEnum.A).
>>
>> by context, the compiler can look first in the scope for 
>> something named A then look in the enum itself and prepend 
>> myEnum internally.
>
> Can you expand on "then look in the enum itself"? Which enum? 
> How to find the correct myEnum, if there is also myEnum2 and 
> myEnum3?

I think he means that function 'test' is declared with a 
parameter of type 'myEnum',
so the only two scopes to look up are the current one and the 
correct enum 'myEnum', because other enums won't match the 
function parameter type.
If there are two overloads of 'test', with different enums that 
share a member name, the compiler complains about ambiguity.
But maybe this is difficult to accomplish in the compiler, and 
not worth the advantage.

> The problem with implicit lookups is that you might 
> accidentally insert bugs when editing somewhere else. This is 
> why D forbids shadowing variables in general. For example:

With the behaviour I wrote above, there would be no way to insert 
bugs; the worst thing would be the compiler rejecting the line as 
wrong, even if you didn't touch it.

> class Foo {
>   int x;
>   void bar(int a) {
>     baz(x);
>     return a+1;
>   }
> }
>
> Now imagine someone changed the variable "a" into "x". That 
> would change the behavior of "baz(x)" although you did not 
> change the line at all. I have the habit to always prepend this 
> as in "this.x" from Python. It avoids such errors.
>
> Back to enums: If someone inserts another myEnum42 which also 
> has A, the code might suddenly pick the wrong A. The other way 
> round, if you delete myEnum, maybe it finds another A somewhere 
> else. The with-statement makes this explicit and thus more 
> reliable with respect to changes elsewhere.

It wouldn't be ambiguous (as I said above).

Nonetheless, I'm not a huge fan of this extension request.


More information about the Digitalmars-d mailing list