Treating a slice as an InputRange

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Nov 16 11:03:46 UTC 2017


On Wednesday, November 15, 2017 22:48:12 unleashy via Digitalmars-d-learn 
wrote:
> On Wednesday, 15 November 2017 at 21:02:35 UTC, Jonathan M Davis
> wrote:
> > If you specifically want a function to accept a range and
> > mutate it without returning it, then it should take its
> > argument by ref. Having it take auto ref is actually quite odd,
> > since that means that the behavior can depend on whether an
> > lvalue or rvalue is passed in.
>
> I was under the impression that templated parameters needed `auto
> ref` to work as `ref` properly. Good to know that's not true.

What auto ref does is make it so that the parameter is infered as ref if the
argument is an lvalue and infered as non-ref if it's an rvalue. That way,
lvalues get passed by references, and rvalues get moved. It's really not the
sort of thing you use when you intend to mutate the parameter. It's either
used with the intent of avoiding copying (similar to when you use const T&
in C++), or it's used to forward the refness of the argument (e.g. that's
important with something like emplace, which forwards the arguments to the
constructor of the type being constructed).

Because auto ref generates different template instantiations based on the
refness of the type, it only works with templated functions, but ref in
general doesn't function any differently with templates than it does with
non-templates.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list