Why D is annoying =P

H. S. Teoh hsteoh at quickfur.ath.cx
Wed Oct 24 20:20:14 PDT 2012

On Thu, Oct 25, 2012 at 04:46:04AM +0200, Era Scarecrow wrote:
> On Thursday, 25 October 2012 at 02:19:39 UTC, H. S. Teoh wrote:
> >Huh? Why would you drop classes in favor of structs? They are used
> >for two different purposes. Classes are for when you need
> >polymorphism: inheritance, overloading, interfaces, all the trappings
> >of OO programming. Structs are for when you need value types that
> >doesn't need OO-style manipulations. Not the same thing.
>  Indeed. Instead of interfaces you'd use templates, OO doesn't change
>  really all that much. There's also large amounts of memory
>  consumption  that just isn't needed for data that hasn't and/or isn't
>  going to change. More often I'm thinking structs w/templates are more
>  powerful than classes.

Used correctly, *classes* with templates can be pretty powerful too.

Recently I wrote an expression parser that can either parse the
expression into a tree, or compute its value on-the-fly. I didn't like
the idea of duplicating the parser code for both usages, so I decided to
turn the parser into a template that would do one or the other. The
template would call a static class method at key points during the
parse, which alleviates the parser from knowing (or caring) what was
done with the parsed expression -- the method could build a tree, or
evaluate the expression, etc..

While I was coding that, I realized that lots of code is still being
duplicated -- for example, to implement building a tree with +, -, *,
and / operators _and_ to evaluate the same operators on-the-fly,
required that operator-specific code be written in both classes. That
was when I realized that I can leverage inheritance by factoring the
operator-specific code into the base class, and overriding the static
method in the derived class so that when the parser was instantiated
with the base class, it built an expression tree, whereas when
instantiated with the derived class, it would evaluate the expression.
And moreover, the return type of the parser would be the derived class,
so the caller doesn't even need to downcast to read the computed value.
And all the while, the derived class can also be used as leaf nodes in
the full expression tree, when building the latter.

So even though things like templated virtual methods don't work, you
*can* still make pretty potent combinations of templates + classes.


Doubtless it is a good thing to have an open mind, but a truly open mind
should be open at both ends, like the food-pipe, with the capacity for
excretion as well as absorption. -- Northrop Frye

More information about the Digitalmars-d mailing list