[LC++]Generic programming vs OO inheritance
mark at austrics.com.au
Mon Aug 20 17:29:26 UTC 2001
Dan hursh wrote:
> Oh, lets talk. I was going to accept having you "almost convinced"
> until you went into that whole bit about all the information being
> available at compile time for OO inheritance. The time when polymorphism
> (since that is what we are talking about here) is most needed is when you
> don't know at compile time, what you will have.
Okay, I think you have "fully convinced" me. Template implemented
polymorphism works except when you really do need non-constant
__pointers__ to a base type. Having a pointer to a base type allows
you to effectively have a variable which takes on different classes
at runtime. This effectively allows you to have function variables,
ie a variable which is assigned to different functions at runtime.
To achieve this --- runtime variability --- virtual functions are
what you need. If function assignments are all known at compile
time, then you can use template ideas to achieve _static_
Hopefully I have things correct in my mind now.
Thanks for your help.
> What would be cool is if some template evaluation could be done a
> runtime, but I guess that would defeat the purpose of templates wouldn't
> it. It still might be nice a link time.
I think there is a sense in which "template evaluation could be done at
runtime" --- well sort of. But to achieve it would require a willingness
to throw out the long held notion that "self-modifying code is bad".
Consider the case where you have an n x n matrix. If you know the size
of n at compile time, you can use templates to create specialized
algorithms for dealing with this sized matrix --- leading often to
much faster code. But what happens if you only know the size of n
at compile time --- after reading it in from a configuration file
for example. Well, you can't use specialized algorithms anymore. You
need to store n as a variable and make any algorithm deal with the
cases of arbitrary such n. But imagine the following solution...
You read in the value of n from a file. At _run_time_ you form some
specialized code, similar to the way this is done at compile time
with templates. Once these specialized algorithms have been
produced, they can be executed to your heart's content, and with
the same efficiency that compile time specialization brings. The
only overhead is the runtime creation of code --- but if this is
done only occasionally through the life of the program, it will be
It was a sad day when computer scientists decided self modifying
code was _always_ bad.
More information about the tuxCPProgramming