简体   繁体   中英

When is a `value_type` of an iterator used?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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