我尝试为我的一个类实现迭代器,令人惊讶的是我得到了以下结果:
警告:ISO C++ 说这些是模棱两可的,即使第一个的最差转换优于第二个的最差转换
候选1:'Iterator Iterator::operator+(const ptrdiff_t&) [with T = int; ptrdiff_t = long long int]'
候选 2:'operator+(int, unsigned int)'
这是Iterator
代码:
template<typename T>
class Iterator {
public:
Iterator(T *p = nullptr) { this->ptr = p; }
Iterator(const Iterator<T>& iter) = default;
Iterator<T>& operator=(const Iterator<T>& iter) = default;
Iterator<T>& operator=(T* p) { this->ptr = p; return *this; }
operator bool() const { return this->ptr ? true : false; }
bool operator==(const Iterator<T>& p) const { return this->ptr == p.getConstPtr(); }
bool operator!=(const Iterator<T>& p) const { return this->ptr != p.getConstPtr(); }
Iterator<T>& operator+=(const ptrdiff_t& v) { this->ptr += v; return *this; }
Iterator<T>& operator-=(const ptrdiff_t& v) { this->ptr -= v; return *this; }
Iterator<T>& operator++() { ++this->ptr; return *this; }
Iterator<T>& operator--() { --this->ptr; return *this; }
Iterator<T> operator++(int) { auto temp(*this); ++this->ptr; return temp; }
Iterator<T> operator--(int) { auto temp(*this); --this->ptr; return temp; }
Iterator<T> operator+(const ptrdiff_t& v) { auto oldPtr = this->ptr; this->ptr += v; auto temp(*this); this->ptr = oldPtr; return temp; }
Iterator<T> operator-(const ptrdiff_t& v) { auto oldPtr = this->ptr; this->ptr -= v; auto temp(*this); this->ptr = oldPtr; return temp; }
ptrdiff_t operator-(const Iterator<T>& p) { return std::distance(p.getPtr(), this->getPtr()); }
T& operator*() { return *(this->ptr); }
const T& operator*() const { return *(this->ptr); }
T* operator->() { return this->ptr; }
T* getPtr() const { return this->ptr; }
const T* getConstPtr() const { return this->ptr; }
private:
T *ptr;
};
这就是我typedef
在课堂上的表现:
template<typename T>
class ExampleClass {
public:
// ...
typedef Iterator<T> iterator;
typedef Iterator<const T> const_iterator;
// ...
iterator begin() { return iterator(&this->ptr()[0]); }
iterator end() { return iterator(&this->ptr()[this->size()]); }
const_iterator cbegin() { return const_iterator(&this->ptr()[0]); }
const_iterator cend() { return const_iterator(&this->ptr()[this->size()]); }
// ...
// A function where I use the operator+
void slice(unsigned int first, unsigned int last) {
// ...
auto it = this->begin() + first; // <--------
// ...
}
};
也许我遗漏了一些东西,但是如何(Iterator, ptrdiff_t)
并且(int, unsigned int)
模棱两可?