From slices to perfect imitators: opByValue

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Thu May 8 03:50:49 PDT 2014


On Thu, 08 May 2014 12:38:44 +0200
Timon Gehr via Digitalmars-d <digitalmars-d at puremagic.com> wrote:

> On 05/08/2014 08:55 AM, Jonathan M Davis via Digitalmars-d wrote:
> > As far as I can see, opByValue does the same thing as opSlice,
> > except that it's used specifically when passing to functions,
> > whereas this code
> >
> > immutable int [] a = [1, 2, 3];
> > immutable(int)[] b = a[];
> >
> > or even
> >
> > immutable int [] a = [1, 2, 3];
> > immutable(int)[] b = a;
> >
> > compiles just fine. So, I don't see how adding opByValue helps us
> > any. Simply calling opSlice implicitly for user-defined types in
> > the same places that it's called implicitly on arrays would solve
> > that problem. We may even do some of that already, though I'm not
> > sure.
>
> Automatic slicing on function call is not what actually happens. You
> can see this more clearly if you pass an immutable(int*) instead of
> an immutable(int[]): there is no way to slice the former and the
> mechanism that determines the parameter type to be immutable(int)* is
> the same. (And indeed doing the opSlice would have undesirable
> side-effects, for example, your pet peeve, implicit slicing of
> stack-allocated static arrays would happen on any IFTI call with a
> static array argument. :o) Also, other currently idiomatic containers
> couldn't be passed to functions.)

Ah, you're right. The fact that slicing an array results in tail-const array
is part of the equation, but implicit slicing isn't necessarily (though in the
case of IFTI, you still get an implicit slice - it's just that that's a side
effect of what type the parameter is inferred as).

Still, the core problem is that MyRange!(const T) is not the same as
const(MyRange!T), and that needs to be solved for opSlice to work properly.
I'd still be inclined to try and just solve the problem with opSlice rather
than introducing opByValue (maybe by having a UDA on opSlice which indicates
that it should be implicitly sliced in the same places that a dynamic array
would?), but as you point out, the problem is unfortunately a bit more
complicated than that.

- Jonathan M Davis


More information about the Digitalmars-d mailing list