Programming Challenge
Bill Maguire
maguire at sun.soe.clarkson.edu
Tue Dec 18 06:20:20 AEST 1990
In article <1990Dec15.015355.15683 at fmrco> harold at fmrco (Harold Naparst) writes:
>I am trying to write a function which will return the index
>of the smallest element of an array. I want the routine
>to work for any type array. That is, I don't want to write
>a separate routine for each type of array (real or double or
>integer). How can I do this ? I tried playing around with
>the GNU C typeof operator, but couldn't figure it out. Any ideas ?
>Harold Naparst
Tw ways immediately pop to mind:
1) overload the function to take a real*, double* or integer*. You'll
have to do some text editing to copy the code and replace the types
but this is where templates come in. With templates you can write
only one of the functions and the compiler will generate the
completed function definitions as you use them.
(This isn't entirely true in GNU g++ yet, there is a SED script, I
believe, that given a template will generate the function definitions
that you ask of it)
2) The problem with having the same "compiled code" work on an array
of real, double, or integer is that these objects are in no way
related through any hierarchy. So any call to the function cannot
be resolved polymorphically at run time. To correct this create a
hierarchy of Numbers with Number as an abstract base class. You will
have to do a lot of work defining the operators between numbers as it
will take two virtual calls to resolve the type of each operand.
At this point you can create an Array of Number object. Now write
the function to work on an Array of Number. This will be slower than
the first example as a great deal of polymorphic calls will have to be
made, but less compiled code will be generated. (Not really, as you
have to add the code for your whole type hierarchy) Another "problem"
with this solution is that the Arrays are no longer limited to one type,
you could have Integers, Reals, and Doubles in the same list. Not
quite what you want.
However you could do some more work and define the classes
Array of Integer, Array of Real, and Array of Double as subclasses of
Array of Number. These class would have to know what to do if they
were asked to set an element to the wrong type (i.e error),
(Actually if you were using an overload operator[] and passing back
a reference as an lvalue than this can be resolved in the Number class)
but they could be implemented much more efficiently than a straight array
of number.
Now you have what you want. A lot of work though.
Bill Maguire
sun.soe.clarkson.edu
She had so many chins, she looked like a piece of lisp code :-))))))
More information about the Comp.lang.c
mailing list