'struct std::iterator_traits<int* const>' 中没有名为 'iterator_category' 的类型

No type named 'iterator_category' in 'struct std::iterator_traits<int* const>'

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

#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>相比有什么区别?

问题可以简化为:

#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;
}

Live demo