"the last change" for ranges

Bill Baxter wbaxter at gmail.com
Wed May 20 09:57:16 PDT 2009


On Wed, May 20, 2009 at 9:19 AM, Andrei Alexandrescu
<SeeWebsiteForEmail at erdani.org> wrote:

> I'm thinking a better design is to require any range that's forward or
> better to define a function save(). Ranges that don't implement it are input
> ranges; those that do, will guarantee a brand new range is returned from
> save(). So then adjacentFind would look like this:
>
> R adjacentFind(R)(R r)
> {
>    if (r,empty) return r;
>    R last = r.save;
>    r.popFront;
>    for (; !r.empty && last.front != r.front; last.popFront, r.popFront)
>    {
>    }
>    return r;
> }
>
> Obviously, when you pass a range that doesn't support save, adjacentFind
> will not compile, which is what we want.

The only other alternative that comes to mind would be forcing input
ranges to hide their copy constructor, or whatever the D equivalent
is, making R last = r; fail.  But that would make input ranges very
difficult to use.

So, of those two options at least, requiring a .save sounds like the
better choice.

The down side is you will get no error if you write the code the first
way, without a .save.   I see this as turning into tip #5 in
"Effective D" -- "Know when to use .save"   It would be nice if that
potential mistake could be eliminated somehow.  You could perhaps
require input ranges to implement transfer semantics, and have them
implement a .clone for cases when you really do want to make an
aliasing copy.

--bb



More information about the Digitalmars-d mailing list