lundi 2 janvier 2017

Access data from base class with the correct typecasting of it derived templated class

I have the following scenario:

class ScalarField
{
   void* _buffer; //Array for data.
};

And a derived class:

template <typename T> 
class ScalarFieldT : public ScalarField
{
    ScalarFieldT(int size)
    {
       _data = new T[size];
       _buffer = _data;
    }

   T& get(int index)
   {
       return _data[index];
   }

   T* _data; // Typed array for data
};

Notice that T can assume only basic types such float, int, double and so on.

This is a very old legacy code, so I don't have too much flexibility to adjust it properly doing a better design. What a need to do is to access the data from ScalarField::_buffer with the correct typecasting of it derived class.

Something like this:

void main()
{
   int n = TOTAL_SIZE;
   ScalarFieldT<int> typedScalarField(n);

   ScalarField* scalarField = &typedScalarField;

   // This is what I need to do:
   int index = ELEMENT_INDEX;        
   float value = scalarField->method(index); // Get the value from base class correctly converted from int to float, for example.       
}

The point is, I only have access to the base class abstraction, but I need to get the value from _buffer converted to another simple data type, such float, int, uchar, etc.

What do you guys recommend?

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire