Understanding Templates: why can't anybody do it?

Nick Sabalausky a at a.a
Sat Mar 17 18:00:54 PDT 2012


"H. S. Teoh" <hsteoh at quickfur.ath.cx> wrote in message 
news:mailman.839.1332031513.4860.digitalmars-d at puremagic.com...
> On Sat, Mar 17, 2012 at 08:37:35PM -0400, Nick Sabalausky wrote:
>> "H. S. Teoh" <hsteoh at quickfur.ath.cx> wrote in message
>> news:mailman.834.1332023905.4860.digitalmars-d at puremagic.com...
>> >
>> > (Not to mention, D templates can do some stuff that no OO can hope
>> > to attain. But it goes both ways. Templates can't do runtime
>> > polymorphism either.)
>> >
>>
>> Combined with compile-time reflection, I'm sure they could be used to
>> create a runtime polymorphism tool, even multiple dispatch. Like I
>> mentioned recently in a seperate thread, you'd just need to use
>> templates/ctfe to automate/genericize this:
>>
>> void singleDispatch(Object o)
>> {
>>     if(auto derived = cast(DerivedClassA)o)
>>         derived.foo();
>>     else if(auto derived = cast(DerivedClassB)o)
>>         derived.foo();
>>     else if(auto derived = cast(DerivedClassC)o)
>>         derived.foo();
>>     //etc...
>> }
>>
>> Although I guess *technically* you're still relying on OO polymorphism
>> (in the form of downcasting) to achieve this. OTOH, you could still
>> base it on Variant or Algebraic instead of (or in addition to) Object.
>> Then you'd have built runtime polymorphism out of templates (among
>> other things) without relying on OO.
> [...]
>
> But now you're just reimplementing OO in terms of templates. :-) You can
> do OO in C, too. (In fact, at work some of the C code I deal with are
> approximations to OO.) That has nothing to do with templates themselves
> per se.
>

I'd argue: To view that (particularly if using Variants) as reimplementing 
OO, is to blur the distinction between OO and polymorphism. OO is such a 
popular form of polymorphism that we're conditioned to look at polymorphism 
and say "Oh, that's OO". Really, OO is just one way of doing polymorphism. 
You define a class. You define a subclass and override its methods. Etc. 
Other forms of polymorphism exist, such as defining over*loads* and 
dispatching to them based on the type in a Variant - which, AIUI, is what 
some non-OO polymorphic languages do behind-the-scenes (though I could be 
wrong). Uhh, i *think* ML is one such example. Anyway, these other types of 
polymorphism can easily look like OO because, since they're all just forms 
of polymorphism, they look like they're just variations on the same 
fundamental thing. And that's because they are just variations on the same 
fundamental thing: polymorphism.




More information about the Digitalmars-d mailing list