问题
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 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.
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