When is a `value_type` of an iterator used?

Deadly 提交于 2020-12-08 07:06:40

问题


I am trying to understand when an iterator::value_type is actually used.

Because, all operators of iterators, seem to use only iterator::pointer and iterator::reference.

Question: Is iterator::value_type actually used for something?

Extra question: Would an iterator inherited from

std::iterator<std::random_access_iterator_tag, int, std::ptrdiff_t, bool*, bool&>

raise some semantic issues?

EDIT: 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.


回答1:


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

Of course you can use decltype(*begin) instead, but using value_type looks neat-er and more elegant. In C++14 I cannot think of a really good use, since you can have auto type deduction on function return.

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.



来源:https://stackoverflow.com/questions/33115615/when-is-a-value-type-of-an-iterator-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!