Overriding Template Methods

H. S. Teoh hsteoh at quickfur.ath.cx
Sun Jan 29 19:22:50 PST 2012


On Sun, Jan 29, 2012 at 06:43:39PM -0800, Ali Çehreli wrote:
[...]
> Template member functions cannot be virtual.
> 
> One quick reason why this is so is that Derived.writeValueType would
> have to be instantiated by the compiler, for every possible type in
> the program. This would lead to almost infinitely large virtual
> function pointer table.
[...]

I wonder, though, if there are ways of simulating overridable template
members by clever use of opDispatch().

Having said that, if you ever get to the point where you can't get
around needing overridable template members, then it may be a sign that
you're trying to represent simulated types by language types and
simulated objects by language objects, whereas the two are different
beasts. The solution is to work at a higher level of abstraction.

This kind of thing happens, for example, when you're trying to do, say,
a physics simulation where you have various types of particles that
interact with each other. It may be possible up to a point to represent
each type of particle as a separate class, perhaps with a class
hierarchy of some sort.

But there comes a point where you need to treat simulated types (i.e.,
particle types) as distinct from the programming language's types. I.e.,
you have a Particle class that stores an enum that represents what type
the particle is (not to be confused with the programming language's
types), and perhaps an array of attributes associated with the particle
(as opposed to coding each attribute into a distinct field). Particle
interactions then are handled by a single method that takes a string or
enum type representing what kind of interaction it is, rather than
mapping each interaction to a method.

This kind of implementation is necessary if, say, the particles have
runtime-variable attribute lists, or runtime-variable types, or even
types that emerge at runtime. Or when simulated particles don't really
behave like programming language class objects, and therefore don't map
very well onto the OO paradigm.


T

-- 
Do not reason with the unreasonable; you lose by definition.


More information about the Digitalmars-d-learn mailing list