更新时间:2023-11-28 10:37:28
规范的做法是继承 std :: iterator< std :: forward_iterator_tag ,T>
。迭代器只有一个类别。
The canonical thing to do is to inherit from std::iterator<std::forward_iterator_tag, T>
only. Iterators have only one category.
标准没有用于输出迭代器(也是向前迭代器)的算法(或其他用法)。在标准中,输出迭代器的所有使用只需要单次传递。
The standard has no algorithms (or other uses) for an output iterator that is also a forward iterator. All uses of output iterators in the standard require only single-pass.
而是,标准具有类别forward / bidi / randomaccess的可变对不可变迭代器的想法。所有需要通过迭代器编写的算法,并且需要优于单遍的算法,也可以通过它们通过的相同迭代器来读取。这是 std :: remove
, std :: sort
和其他变异算法。
Instead, the standard has the idea of mutable vs. immutable iterators of categories forward/bidi/randomaccess. All the algorithms that need to write through iterators, and that require better than single-pass, also read through the same iterators they write through. This is std::remove
, std::sort
and other mutating algorithms.
可变和不可变迭代器之间的区别不是通过迭代器标签检测,它是由赋值表达式是否形式确定。因此,例如,如果你通过一个迭代器到 std :: sort
是不可变的,那么算法不会编译反正,所以一般不需要一个输入迭代器也是标记为 output_iterator_tag
。所有需要 OutputIterator
的算法将只使用一个可变的 ForwardIterator
,再也没有必要 output_iterator_tag
。
The difference between mutable and immutable iterators is not detected by iterator tag, it's determined by whether the assignment expressions are well-formed. So for example if you pass an iterator to std::sort
that's immutable, then the algorithm won't compile anyway, so there's generally no need for an input iterator to also be tagged with output_iterator_tag
. All algorithms that require an OutputIterator
will Just Work with a mutable ForwardIterator
, again there is no need for it to be tagged with output_iterator_tag
.
如果你有不同于标准算法的需求,一个原因,你的建议不会为你的迭代器工作。但它不会检测可变标准迭代器。例如 std :: deque< int> :: iterator
和 int *
random_access_iterator_tag ,而不是您的私有标记,而不是与 output_iterator_tag
有关的任何内容。所以你可能会更好地定义自己的traits类,而不是希望适应现有的 iterator_traits :: iterator_category
来提供你想要的信息。
If you have different needs from those of the standard algorithms then I can't immediately think of a reason that your proposal won't work for your iterators. But it won't detect mutable standard iterators. For example std::deque<int>::iterator
and int*
have iterator category random_access_iterator_tag
, not your private tag and not anything to do with output_iterator_tag
. So you would probably be better off defining your own traits class rather than hoping to adapt the existing iterator_traits::iterator_category
to provide the information you want.