input range with non copyable element

vit vit at vit.vit
Sun Aug 8 18:36:02 UTC 2021


Hello, is there reason why elements of input range must be 
copyable?

For example this example works and copy ctor is never called:

```d
import std.algorithm : map;
import std.range;

struct Foo{
	int i;

     this(scope ref typeof(this) rhs)pure nothrow @safe @nogc{
     	//this.i = rhs.i;
         assert(0, "no copy");
     }
	@disable this(scope const ref typeof(this) rhs)pure nothrow 
@safe @nogc;
}


void main(){
     Foo[] foos = [Foo(1), Foo(2), Foo(3)];

     //this work (copy ctor is never called):
     {
         auto tmp = foos
             .map!((ref foo) => foo.i)
             .array;
     }
}
```

This doesn't work:


```d

void main(){
     const(Foo)[] foos = [Foo(1), Foo(2), Foo(3)];

     //error:
     {
         auto tmp = foos
             .map!((ref foo) => foo.i)
             .array;
     }
}
```

Source of my problem is in `isInputRange`:
```d
import std.range;
import std.traits : ReturnType;

alias R = const(Foo)[];
//enum bool isInputRange(R) =
static assert(is(typeof(R.init) == R));								///OK
static assert(is(ReturnType!((R r) => r.empty) == bool));			///OK
static assert(is(typeof((return ref R r) => 
r.front)));				///ERROR, copy result of front
static assert(!is(ReturnType!((R r) => r.front) == void));			///OK
static assert(is(typeof((R r) => r.popFront)));						///OK
```

Is it possible to make lambda return `auto ref`?


More information about the Digitalmars-d-learn mailing list