mercredi 25 octobre 2017

How do I dynamically allocate space in a template class without violating const restrictions?

This is my first experience with templates, consider this a newbie question (please).

What I would like to do is to keep the convenience of using operator[] but structure the function to dynamic array growth, e.g., . I keep getting trashed with const violation errors. I would have preferred to use but I cam across a runtime error whenever I did an x[ndx] = value. I finally gave up and am trying to creae my own version of .

The example code is:

#ifndef VECTOR_H
#define VECTOR_H

using namespace std;
template <typename T>
class  Vector {
   private:
      long _ndx = 0;
      T*    _ptr;                               // storage for T objects
   public:
      Vector() { }
      T&   operator[](const long ndx) { _ndx = ndx; return _ptr[ndx]; }
 };
#endif   // VECTOR_H


# include <iostream>

# include "Vector.h"

using namespace std;

struct X {
   long a;
   long b;
   void toString() { cout << a << " " << b << endl; }
};

class Y {
private:
   long _ndx =0;
   Vector<X*> word;
public:
   Y() { }
   X* operator[](const long ndx) const {  return word[ndx]; }
};

int main(int argc, char** argv) {
   Y y;
   X* x = y[0];
}

The error is:

    main.cpp:20:58: error: passing 'const Vector<X*>' as 'this' argument
    discards qualifiers [-fpermissive]
    X* operator[](const long ndx) const {  return word[ndx]; }

   In file included from main.cpp:4:0: Vector.h:13:12: note:   in call to 'T&
       Vector<T>::operator[](long int) [with T = X*]'
    T&   operator[](const long ndx) { _ndx = ndx; return _ptr[ndx]; }

From other questions on stackoverflow I understand the error. I haven't been able to get -fpermissive to work. The actual code changes Vector::operator[] to do two things, adjust the high water mark for _ndx and, when _ndx exceeds some threshold, increase the vector size, here T* _ptr, copy the old information into the new space and delete the vector and use the new space. I can't figure how to do this 'gracefully'.

Aucun commentaire:

Enregistrer un commentaire