Suggestions for multiple class members with the same name

Michiel Helvensteijn nomail at please.com
Tue Aug 12 16:02:38 PDT 2008


bobef wrote:

> Hi, the suggestions is this:
> 
> In this case:
> 
> class A
> {
>   uint a(char[] b){}
>   int a(int b){}
> }
> 
> Make this syntax valid:
> 
> A.a[1]
> A.a.length
> etc

There's a very complicated variation of this idea and a slightly less
complicated one.

The less complicated variation: The index always has to be an expression
that can be easily evaluated at compile-time (like a literal or a
constant). That way, every member-reference can be fully qualified at
compile-time. However, if this is the behavior you want, you might as well
call the members A.a1 and A.a2. I believe the D template system allows you
to use a syntax like A.a!(1) and A.a!(2) in this case (though I haven't
used D in quite a while, so I'm not sure). And the .length property would
not be very useful in this variation.

So I'm guessing you are suggesting a more complicated variation, in which
the index can be any integer expression. The problem here is that the
compiler can not always know what to expect when A.a[i] is called. The
function might take or return incompatible types (like char[] vs. int).
Either you'd have to make sure the code at the call-site is compatible with
any value of 0 <= i < length, or you'd have to guarantee that i will have a
value such that the function-call is correct. This is not a condition that
the compiler will be able to verify, and an error might result in very
strange run-time behavior. I suppose you can work around this last problem
by assert()ing a compatible state of i before the call.

But I believe that in both cases the idea is more trouble than it's worth.
Can you give an example in which it might be useful?

-- 
Michiel




More information about the Digitalmars-d mailing list