Walter: extend existing classes with new methods?

Marcio mqmnews123 at sglebs.com
Fri Sep 8 11:49:37 PDT 2006


> In C++ I used my "fastdelegate" template (on CodeProject) to hack 
> delegates into C++. This lets you do something vaguely like:
> 
[...]
> Then, you can write
> 
> void myfunc(StringWithURL s) {}
> 
> and it will accept anything derived from String. 


    I want existing String objects, belonging to class String, to be 
able to understand asURL. Not a new class. Unless I misunderstood your 
explanation. My understanding is that "derived from String" does not 
include String.


> It's unnecessarily 
> inefficient, though -- not as lightweight as it should be.
> Also things like delete don't work (they don't delete the base class).


   If you could just add methods to the class, these methods would 
behave the same as the ones defined in the class itself. No speed penalty.

   The feature request is quite simple actually. Allow a class C to be 
defined not just in 1 file, but in N files. From many fragments. A class 
is never a closed module in this case.


>>     Another scenario I would be interested to see working is how I can 
>> have Object return false to "isWidget" but a Widget class return true.
> 
> Yeah, that's very common. Some cases can be done very easily:
> 
> template (X)
> void myfunc(X x) {
> static if ( is( x.isWidget ) ) {
>     ...
> }
> }
> 
> but if you don't know the type at compile time, you're stuck.


    Yeah, I'd rather just rely on polymorphism. Which can be done if the 
source of a class can be split across multiple files. These extra 
methods become regular methods, not second class.

> It's very imperfect, but might generate ideas.


    Indeed. But in my mind, a compiler can do lots of interesting things 
after compiling the full program. These extension methods would not be 
hard. There are also all sorts of polymorphism optimizations that can be 
done. SmartEiffel (used to be SmallEiffel) does all sorts of virtual 
call optimizations because it can do a global analysis of thr code 
(something Java can't do, for example, because of thr dynamic class 
loading etc). Sometimes their compiler eliminates 98% of virtual calls. 
It generates amazingly fast code.

   Anyway, just to say that if you are compiling a program to generate 
an EXE, with no fancy dynamic loading etc, it should be possible to do 
these global analysis and therefore also allow methods to be added from 
different places. Like extending a framework by adding methods to base 
classes so that all subclasses now receive the extra behavior. And that 
includes Object itself.

  In dynamic languages, it is a no-brainer of course.

  Anyway, I wish D had this. It's a powerful mechanism to have. But 
since Walter did not reply at all, I guess he does not like the idea. Oh 
well...


marcio





More information about the Digitalmars-d mailing list