什么时候使用迭代器的"value_type"? [英] When is a `value_type` of an iterator used?
问题描述
我试图了解何时实际使用iterator::value_type
.
I am trying to understand when an iterator::value_type
is actually used.
因为,所有迭代器运算符似乎仅使用iterator::pointer
和iterator::reference
.
Because, all operators of iterators, seem to use only iterator::pointer
and iterator::reference
.
问题:iterator::value_type
是否确实用于某物?
Question: Is iterator::value_type
actually used for something?
其他问题:迭代器是否继承自
std::iterator<std::random_access_iterator_tag, int, std::ptrdiff_t, bool*, bool&>
引发一些语义问题?
编辑:要理解为什么我问这个问题,是因为我正在为类型为pointer
和reference
是代理类的迭代器进行工作.
To understand why I am asking this question, it's because I am working on an iterator for a type for which pointer
and reference
are proxy classes.
推荐答案
我可以考虑在通用代码中使用它.假设您正在编写一个通用函数,该函数总结了C ++ 11中的范围.您可以将其写为
I can think of using it in generic code. Suppose you're writing a generic function that sums up a range in C++11. You can write it as
template<typename It>
auto sum(It begin, It end) -> typename It::value_type
{
typename It::value_type _sum{};
// compute the sum
return _sum;
}
您当然可以使用在C ++ 14中,我无法想到一个很好的用法,因为您可以在函数返回时具有自动类型推断.decltype(*begin)
代替,但是使用value_type
看起来更整洁,更优雅.
Of course you can use In C++14 I cannot think of a really good use, since you can have auto type deduction on function return.decltype(*begin)
instead, but using value_type
looks neat-er and more elegant.
编辑正如@Luc Danton在评论中提到的那样,大多数时候使用decltype(*begin)
会产生引用,因此您需要std::remove_reference
,这看起来很讨厌.所以value_type
派上用场了.
EDIT As mentioned by @Luc Danton in the comment, using decltype(*begin)
yields a reference most of the time, so you'd need to std::remove_reference
, which makes it look quite nasty. So value_type
comes handy.
这篇关于什么时候使用迭代器的"value_type"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!