[LC++]Static polymorphism and arrays of poly. objects

Davide Bolcioni 9odb6x3rfr001 at sneakemail.com
Wed Aug 22 08:28:04 UTC 2001


Mark Phillips mark at austrics.com.au [mltuxcpp/linux-cpp list] wrote:


> But what happens if I want to have an __array__ of
> these leaf "function" objects?


First, as others suggested you need to have operator() virtual
since you're no longer after compile-time polymorphism only.
Note that, in my experience, you want compile-time polymorphism
when only one of the polymorphic variants gets actually
compiled (you're testing variant approaches, for example); if multiple
implementations end up being compiled, it's likely you need
runtime polymorphism also.

 
> Ie suppose instead of wanting to write a generic algorithm
> taking one functionLeafType as a parameter, I want it
> to take an array of these leaf objects, where the size of
> this array, and the objects that are to go in it, are known
> at compile time?


Agreed.

 
> The problem is, I can't yet see how it would be done.
> 
> My thoughts are that it would be something along the
> following lines:
> 
>   functionBaseTy* myArray[] = {squareTy(), twiceTy(), thriceTy()}
>   
>   template<functionBaseTy* leafArrayType[]>
>   void myAlgorithm......


The following code is untested but might be a start:

   // Objects need to be allocated somewhere

  squareTy square;

   twiceTy twice;
   thriceTy thrice;

   functionBaseTy* fns[] = { &square, &twice, &thrice };

   template <class T, int N>
   inline
   void my_algorithm(T* functions[N])
   {
     // This deduces T and the array size N
     my_real_algorithm(functions, N);
   }

 

   template <class T> // not inline
   void my_real_algorithm(T* functions, int n)
   {
     // Loop here ...
   }

The above illustrates a workaround for a typical template problem: with 
argument deduction, you end up with a different inline copy for each
value of N (and T, but you typically want this) - but looping N times
is not any faster when N is a constant (but note below) so you want
all instantiated functions inline and calling a non-inline 
implementation (unless the algorithm is so simple that inlining it
also works).

Davide Bolcioni
-- 
There is no place like /home.




More information about the tuxCPProgramming mailing list