自定义迭代器

时间:2018-08-28 16:40:42

标签: c++ iterator gcc8

我尝试为我的一类实现迭代器,令人惊讶的是,我得到了以下内容:

  

警告:ISO C ++表示这些含义不明确,即使第一个转换最差比第二个转换最差

     

候选人1:“迭代器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)是如何模棱两可的?

1 个答案:

答案 0 :(得分:2)

我还没有编译这个,但是问题似乎是operator bool();它提供了对bool的隐式转换,进而可以转换为int。迭代器通常不提供自己的验证,因此这是不寻常的。如果需要,请标记为explicit。这样可以防止隐式转换。

相关问题