0

我正在编写一个自定义矢量类:

#include <iterator>

template <typename T>
class vector {
 public:
  using value_type = T;
  using pointer = value_type*;
  using iterator = pointer;
  using const_iterator = const iterator;
  using const_reverse_iterator = std::reverse_iterator<const_iterator>;

  auto crbegin() const -> const_reverse_iterator {
    return const_reverse_iterator(data_);
  }

 private:
  pointer data_{};
};

int main(int argc, char* argv[]) {
  vector<int> v;
  auto i = v.crbegin();

  return 0;
}

编译上面的代码时,我收到此错误(在 GCC 和 MSVC 上):

error: no type named ‘iterator_category’ in ‘struct std::iterator_traits<int* const>’

当我将反向迭代器定义更改为std::reverse_iterator<const T*>. 相比有什么区别std::reverse_iterator<const_iterator>

4

1 回答 1

1

问题可以简化为:

#include <iterator>

template <typename T>
class vector {
 public:
  using value_type = T;
  using pointer = value_type*;
  using const_reverse_iterator = std::reverse_iterator<const pointer>;

  auto crbegin() const -> const_reverse_iterator {
    return const_reverse_iterator(data_);
  }

 private:
  pointer data_{};
};

int main() {
  vector<int> v;
  auto i = v.crbegin();
  (void) i;
  return 0;
}

而来自 clang 的错误信息让问题的本质更加清晰:

no type named 'reference' in 'std::iterator_traits<int *const>'
^^^^^^^^^^

所以我们看到你认为的一个const *int(即指向的对象是const)实际上是一个int *const(即指针本身是const)。

这是一个简单的修复:

#include <iterator>

template <typename T>
class vector {
 public:
  using value_type = T;
  using pointer = value_type*;
  using const_pointer = const value_type*;
  using const_reverse_iterator = std::reverse_iterator<const_pointer>;

  auto crbegin() const -> const_reverse_iterator {
    return const_reverse_iterator(data_);
  }

 private:
  pointer data_{};
};

int main() {
  vector<int> v;
  auto i = v.crbegin();
  (void) i;
  return 0;
}

现场演示

于 2021-11-21T18:44:07.267 回答