Idea: Lazy upcasting

Chris Nicholson-Sauls ibisbasenji at gmail.com
Tue Mar 27 01:33:34 PDT 2007


Mitja Slenc wrote:
> Aarti_pl wrote:
> 
>> Proposition has also nothing to do with implicit downcasting. It has 
>> more with upcasting, but in opposite way - implicit upcasting should 
>> be disallowed in some cases :-)
>>
>> If my proposition is not clear in some aspects, feel free to ask 
>> questions. I am not a native speaker, so parts of this proposition 
>> could be unclear...
> 
[...snip...]
> A better idea would be to use a special keyword for the return type to 
> indicate what is going on:
> 
> class Base
> {
>     return_this foo(int i) { ... }
> }
> 
> class Derived : Base
> {
>     return_this bar(int i) { ... }
> }
> 
> void main()
> {
>     Derived d = (new Derived).foo(1).bar(2); // currently an error
> }

I was thinking roughly the same thing, although maybe we could use an operator like symbol 
rather than a keyword.  Something like '@' maybe, where 'Object@' would read as "Object, 
or anything derived there-from."

class Base {
   Base@ foo (int i) { ... }
}

And make the general rule that such return types are implicitly cast to the lowest 
possible class.  When used for type-inferance, however, they should probably still count 
as the highest class... that could be an issue.  For example:

Given...
Base@ someFunc () { ... }

This should work so long as someFunc returns a Derived.
Derived obj = someFunc();

And this should also work, but type 'obj' as a Base.
auto obj = someFunc();


If D had an 'instanceof' operator or close equivelant, it would've made a nice re-usable 
for this case.  Alas.

-- Chris Nicholson-Sauls



More information about the Digitalmars-d mailing list