I have been trying to write my own vector class to better understand C++ templates and iterators, but have been stuck with this error for a while and would really appreciate the help.
The code fails at the second to last line where I call the overloaded operator -.
Code: (Simplified)
#include <memory>
template <typename T>
struct MyVector {
struct iterator {
T* ptr;
iterator(T* p) : ptr(p) {}
};
std::unique_ptr<T[]> data;
size_t size;
MyVector() : data(nullptr), size(0) {}
MyVector(size_t sz) : size(sz) {
data = std::make_unique<T[]>(size);
}
iterator begin() {
return iterator(data.get());
}
iterator end() {
return iterator(data.get() + size);
}
};
template <typename T>
int operator-(typename MyVector<T>::iterator a, typename MyVector<T>::iterator b) {
return a.ptr - b.ptr;
}
int main() {
MyVector<int> mv(3);
mv.end() - mv.begin(); // fails
}
Error:
so.cpp: In function ‘int main()’:
so.cpp:32:14: error: no match for ‘operator-’ (operand types are ‘MyVector<int>::iterator’ and ‘MyVector<int>::iterator’)
32 | mv.end() - mv.begin();
| ~~~~~~~~ ^ ~~~~~~~~~~
| | |
| | iterator<[...]>
| iterator<[...]>
so.cpp:26:5: note: candidate: ‘template<class T> int operator-(typename MyVector<T>::iterator, typename MyVector<T>::iterator)’
26 | int operator-(typename MyVector<T>::iterator a, typename MyVector<T>::iterator b) {
| ^~~~~~~~
so.cpp:26:5: note: template argument deduction/substitution failed:
so.cpp:32:25: note: couldn’t deduce template parameter ‘T’
32 | mv.end() - mv.begin();
|
first of all, I have done this exact thing before, and I would recommend using a class over a struct, either way, if you want the operator - to work on MyVector.end() - MyVector.begin() it has to go in the iterator struct, and in this case, the operator should have 1 argument, the target. The error mainly came from the compiler not being able to resolve the template because you put one above the operator - function which meant that it expected a type when the function was called, I didn't modify any of your code other than what was required to make this work, because you said that it was a project to learn, here's the fixed and running code: