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

Mark Phillips mark at austrics.com.au
Mon Aug 20 19:08:49 UTC 2001


Suppose I am using templates to implement static polymorphism.
For example, suppose I have the following base type:

template<typename functionLeafType>
class functionBaseTy {
 public:
    functionLeafType& asLeaf() {
      return static_cast<functionLeafType&>(*this);
    }
    int operator()(int i) {return asLeaf()(i);}
};

This is the Barton and Nackman Trick for doing static polymorphism.
It allows us to statically define a whole lot of leaf "function" 
classes, and yet refer to them via a base class.

Example leaf "function" classes might include:

struct squareTy: public functionBaseTy<squareTy> {
  int operator(int i) const {return i*i;}
};

struct twiceTy: public functionBaseTy<twiceTy> {
  int operator(int i) const {return 2*i;}
};

struct thriceTy: public functionBaseTy<thriceTy> {
  int operator(int i) const {return 3*i;}
};

Then you can write the following generic algorithm:

template<typename functionLeafType>
int apply(functionBaseTy<functionLeafType>& f, int i) {
  return f(i);
};

and then write:

squareTy square;
apply(square, i);
twiceTy twice;
apply(twice, i);
thriceTy thrice;
apply(thrice, i);

This algorithm "apply" is pretty basic, but obviously
you could have all sorts of generic algorithms.


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

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?

Well actually, in order for array addressing to work properly,
we will need an array of "constant" pointers to these objects.
For example, I might want an array with three elements in it,
these being square, twice and thrice.  I know everything at
compile time, so I should be able to have a generic algorithm
which takes as an argument, an array of pointers to these
objects, and then pass this array with its three elements, into
this algorithm.  Everything should be able to be handled at
compile time.

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......

but the first line doesn't work and I doubt that the template
line works either.

Any ideas?

Thanks,

Mark.



More information about the tuxCPProgramming mailing list