Re: meta-programming on functions in template class
Richard <legalize+jeeves@mail.xmission.com> wrote:
Juha Nieminen <nospam@thanks.invalid> spake the secret code
<4cded0f0$0$32150$7b1e8fa0@news.nbl.fi> thusly:
Marc <marc.glisse@gmail.com> wrote:
You can have 2 specializations of the class, but you
duplicate plenty of code.
That's what inheritance is for.
Actually, no. Its often thought that "inheritance = reuse", and
although I do that, its not what inheritance is for. Inheritance is
to specify an "IS-A" relationship between two entities. There are
many, many ways to achieve reuse and eliminate duplication, and
although inheritance is one way that can be done, it isn't what
inheritance is "for".
The subject is not necessarily as black and white as you pose it.
In pure object-oriented design (which is not the same thing as
object-oriented programming, although the latter is usually the practical
implementation of the former) what you say is true: We have concepts,
more abstract ones, and more concrete ones, and each inherited class
should be a more concrete (or specialized) version of the base class
(which is more abstract as a concept).
However, when we are talking about object-oriented programming (which,
as said, can usually be thought as a practical implementation of the
object-oriented design), there can be (and is) more than school of
thought: For example, one states that inheritance should be restricted
to the conceptual abstract-concrete "is-a" relationship, and that any
other "abuse" of inheritance is bad programming. Another school of thought
states that inheritance can be used for code reuse, for grouping code
which is common to more than one class into a single base class, so that
it doesn't have to be duplicated (code repetition is, after all, one of
the biggest sins in programming).
These two concepts don't need to be mutually exclusive. In fact, if you
start grouping common functionality into one single base class, if you do
it properly, you will usually find out that this base class can actually
be designed so that it conforms to a pretty good "is-a" relationship with
the derived classes. Even if the "is-a" relationship is not used directly
per se (ie. no code takes a reference/pointer of the base class type), at
a conceptual level it can still work.
If the common functionality consists of public member functions, I can't
think of a better way than inheritance to do this. In fact, I'd still say
that this is exactly what inheritance is for: Grouping public interface
common to more than one class into a single base class. Since the derived
classes automatically inherit this functionality, they *are* of the same
conceptual type as the base class.