Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 736
Vincent Avatar asked Oct 14 '15 02:10

Vincent


1 Answers

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.

like image 197
vsoftco Avatar answered Sep 22 '22 13:09

vsoftco