mercredi 5 août 2015

Modifying a std::vector function (inheritance?)

I'm porting some Fortran90 code to C++ (because I'm stupid, to save the "Why?!").

Fortran allows specification of ranges on arrays, in particular, starting at negative values, eg

double precision :: NameOfArray(FirstSize, -3:3)

I can write this in C++ as something like

std::array<std::array<double, 7>, FirstSize> NameOfArray;

but now I have to index like NameOfArray[0:FirstSize-1][0:6]. If I want to index using the Fortran style index, I can write perhaps

template <typename T, size_t N, int start>
class customArray
{
public:
    T& operator[](const int idx) { return data_[idx+start]; }
private:
    std::array<T,N> data_;
}

and then

customArray<double, 7, -3> NameOfArray;
NameOfArray[-3] = 5.2;
NameOfArray[3] = 2.5;
NameOfArray[4] = 3.14; // This is out of bounds, 
                       // despite being a std::array of 7 elements

So - the general idea is "Don't inherit from std::'container class here'". My understanding is that this is because, for example, std::vector does not have a virtual destructor, and so should not (can not?) be used polymorphically.

Is there some other way I can use a std::array, std::vector, etc, and get their functions 'for free', whilst overloading specific functions?

template<typename T, size_t N>
T& std::array<T,N>::operator[](const int idx) { ... };

might allow me to overload the operator, but it won't give me access to knowledge about a custom start point - making it completely pointless. Additionally, if I were to optimistically think all my customArray objects would have the same offset, I could hardcode that value - but then my std::array is broken (I think).

How can I get around this? (Ignoring the simple answer - don't - just write myArray[idx-3] as needed)

Aucun commentaire:

Enregistrer un commentaire