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();
|
T
be deduced?" The answer you get for that will serve you a lot longer and further. – Midinette