Boost logo

Boost :

From: David Abrahams (david.abrahams_at_[hidden])
Date: 2001-06-30 14:31:59


----- Original Message -----
From: "Douglas Gregor" <gregod_at_[hidden]>

> Hello all,
> I've written a simple iterator adaptor that caches the result of
> dereferencing the underlying iterator. This sort of adaptor is essential
to
> make the transform_iterator adaptor standards conforming.

Not so. transform_iterator_generator generates standard conforming input
iterators.

> Consider, for instance, using std::max_element on a set of input
iterators.
> One would expect that dereferencing the result of a std::max_element call
> will return the maximal value.

No, std::max_element requires forward iterators. Calling it with input
iterators invokes undefined behavior.

> However, if side effects are present in the
> dereferencing of the underlying input iterators.

...then...?

> Using the input caching
> iterator adaptor, max_element works as expected.

Unless it doesn't. If the implementation can detect that your iterator is
still not a forward iterator (which may in fact be the case, even if your
adaptor has iterator_category = forward_iterator_tag), it may refuse to
compile... if you're lucky ;-)

> The code, documentation, and test for the input caching iterator is in the
> vault at:
> http://groups.yahoo.com/group/boost/files/input_cache_iter.zip
>
> The policy is short enough that I'll post it here as well for discussion.

I notice that it places a default-constructibility constraint on T.

> If there is sufficient interest, I'd like to integrate this iterator
adaptor
> with the iterator adaptors library.

This adapter may in fact be useful, but I think you need to think about the
rationale and application a bit more carefully. The one you gave doesn't
seem to work.

-Dave

> Doug
>
> template<typename T>
> class input_caching_policy : public default_iterator_policies {
> public:
> template <class BaseType>
> void initialize(BaseType&)
>

> result_initialized = false;
> }
>
> template <class Reference, class BaseType>
> Reference dereference(type<Reference>, const BaseType& x) const
>

> if (!result_initialized) {
> result = *x;
> result_initialized = true;
> }
>
> return result;
> }
>
> template <class BaseType>
> void increment(BaseType& x)
>

> result_initialized = false;
> ++x;
> }
>
> template <class BaseType>
> void decrement(BaseType& x)
>

> --x;
> result_initialized = false;
> }
>
> template <class BaseType, class DifferenceType>
> void advance(BaseType& x, DifferenceType n)
>

> x += n;
> result_initialized = false;
> }
>
> private:
> mutable T result;
> mutable bool result_initialized;
> };
>
> Info: http://www.boost.org Unsubscribe:
<mailto:boost-unsubscribe_at_[hidden]>
>
> Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/
>
>


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk