samedi 24 février 2018

Strange bug C++ 11 template class

All compiles well. But the output contains a strange error I do not understand. Would be great if someone could help me with that.

main():

vector<PointGeneric<float>> v(3);

for (int i = 0; i < v.size(); i++)
{
   v[i] = {(float)(i*1.1), (float)(i*0.9)};
   cout << "1: v[" << i <<"] = " << v[i] << endl;
}

for (int i = 0; i < v.size(); i++)
  cout << "2: v[" << i <<"] = " << v[i] << endl;

Output:

1: v[0] = (0.000000, 0.000000)
1: v[1] = (1.100000, 0.900000)
1: v[2] = (2.200000, 1.800000)

2: v[2] = (2.200000, 1.800000)
2: v[2] = (2.200000, 1.800000)
2: v[2] = (2.200000, 1.800000)

Template Class: (not my own, taken from "svg-curve-lib" library on github and very slightly modified; in the original context all works well)

template <typename Tx = float, typename Ty = Tx>
struct PointGeneric 
{   
    public:     
      struct x_getter;
      struct y_getter;

      x_getter x{this};
      y_getter y{this};

      PointGeneric() : PointGeneric { 0, 0} {}
      PointGeneric(Tx x, Ty y) : x(this), y(this), _x{x}, _y{y} {};

 ...

   private:
     Tx _x;
     Ty _y;
};

x_getter - struct:

template <typename Tx = float, typename Ty = Tx>
struct PointGeneric<Tx, Ty>::x_getter
{
   public:
      x_getter(PointGeneric *t): thisPointer{t} {};
      operator Tx() const {return this->thisPointer->_x;};
  private:
     PointGeneric<Tx, Ty>* thisPointer;
};

Aucun commentaire:

Enregistrer un commentaire