简体   繁体   English

为什么 std::array::begin 不返回迭代器?

[英]Why does std::array::begin not return an iterator?

I am trying to build a nested iterator template and relied on iterators having various traits like value_type .我正在尝试构建一个嵌套的迭代器模板,并依赖于具有各种特征的迭代器,例如value_type But as it turns out, not all STL types even return iterators with those traits.但事实证明,并非所有 STL 类型都返回具有这些特征的迭代器。 For instance:例如:

#include <array>
#include <type_traits>

template <typename T>
using iterator_t = decltype(std::declval<T>().begin());

static_assert(std::is_same_v<iterator_t<std::array<int, 3>>, int*>);

This code compiles and shows that the actual type of the array iterator is int* .此代码编译并显示数组迭代器的实际类型是int* In that case, how can I still access traits such as value_type etc?在这种情况下,我怎样才能访问诸如value_type等特征?

The standard doesn't specify how the iterator should be implemented and what the exact type it should be.该标准没有指定迭代器应该如何实现以及它应该是什么确切类型。 In fact pointers like int* does satisfy the requirements of the iterator of std::array , so it's quite legitimate for implementation.事实上,像int*这样的指针确实满足std::array的迭代器的要求,所以它的实现是相当合法的。

You can use std::iterator_traits to get the value_type as std::iterator_traits<iterator_t<std::array<int, 3>>>::value_type , it works with pointers too.您可以使用std::iterator_traitsvalue_type获取为std::iterator_traits<iterator_t<std::array<int, 3>>>::value_type ,它也适用于指针。

int* is an iterator as it satisfies all the requirements necessary of an iterator. int*一个迭代器,因为它满足迭代器的所有必要要求。

Informally:非正式地:

  1. You can deference it (unless it's past the final element of the array).你可以尊重它(除非它超过了数组的最后一个元素)。

  2. You can increment it (as it's a pointer in an array).您可以递增它(因为它是数组中的指针)。

  3. You can copy int* to another int* .您可以将int*复制到另一个int*

  4. You can call std::swap with int* as the types.您可以使用int*作为类型调用std::swap

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM