mercredi 6 octobre 2021

Why doesn't operator [] overloading work in my template class?

Edit: I modified some errors pointed by @Caleth @Jarod42 @Snftel. Thanks but not solve the problme.. the problem is

no operator "[]" matches these operands -- operand types are: Vector<double, 2> [ int ]C/C++(349)

=================================================================== I'm writing a vector template with template parameter T and N, and I did operator[] overloading in the class:

// geometry.h
template <typename T, int N>
class Vector {
 public:
  Vector();
  Vector(std::initializer_list<T> list);
  Vector(const Vector& vector);
  Vector& operator=(const Vector& rhs);
  ~Vector();

  T& operator[](std::size_t n);
  const T& operator[](std::size_t n) const;

 private:
  std::array<T, N> data;
};

namespace vector_m {
// I want to limit the template with given type
template <int N>
double Dot(Vector<double, N> v1, Vector<double, N> v2);

Vector<double, 3> Cross(Vector<double, 2> v1, Vector<double, 2> v2);
Vector<double, 3> Cross(Vector<double, 3> v1, Vector<double, 3> v2);
}  // namespace vector_m

Implement:

// geometry.cc
template <typename T, int N>
Vector<T, N>::Vector() : data() {
  data.fill(0);
}

template <typename T, int N>
Vector<T, N>::Vector(std::initializer_list<T> list) : data() {
  if (N == list.size()) {
    std::initializer_list<T>::iterator it = list.begin();
    for (int i = 0; i < N; ++i) {
      data[i] = *(it + i);
    }
  } else {
    data.fill(0);
  }
}

...

template <typename T, int N>
T& Vector<T, N>::operator[](std::size_t n) {
  return data[n];
}

template <typename T, int N>
const T& Vector<T, N>::operator[](std::size_t n) const {
  return data[n];
}

I thought the operator [] should work, but in the second function it did not:

// this works 
template <int N>
double vector_m::Dot(Vector<double, N> v1, Vector<double, N> v2) {
  double sum = 0;
  for (int i = 0; i < N; i++) {
    sum += v1[i] * v2[i];
  }
  return sum;
}

// but this didn't work
Vector<double, 3> vector_m::Cross(Vector<double, 2> v1, Vector<double, 2> v2) {
  double temp = v1[0];// not work
  return Vector<double, 3>({0, 0, v1[0]*v2[1]-v1[1]*v2[0]}); // it said no operator[] matching here Vector<double,2>[size_t]
}

And, I don't know whether it matters, that I didn't write definition in header file because I want to try the explicit instantiation of template class:

// cc
// explicitly instantiate
template class Vector<double, 2>;
template class Vector<int, 2>;
template class Vector<double, 3>;
template class Vector<int, 3>;
template class Vector<double, 4>;

Aucun commentaire:

Enregistrer un commentaire