Using non-copyable types

Yuxuan Shui yshuiv7 at gmail.com
Thu May 23 22:28:30 UTC 2019


On Thursday, 23 May 2019 at 18:18:02 UTC, H. S. Teoh wrote:
> On Thu, May 23, 2019 at 06:05:41PM +0000, Yuxuan Shui via 
> Digitalmars-d wrote:
>> When I try to use non-copyable types, I just get all sorts of 
>> resistance from the standard library.
>> 
>> For example, most of the std.range functions assume the range 
>> is copyable.  std.typecons.Tuple assume all of its types are 
>> copyable.
>> 
>> I tried to use the new copy constructor feature to make a 
>> wrapper that moves by default. But apparently copy 
>> constructors are ignored when postblit is disabled.
>> 
>> How can we make using non-copyable types easier?
>
> Wrap them in a reference. I.e., instead of passing the range 
> itself, pass a pointer to the range. Or use a suitable wrapper 
> struct with reference semantics.  Thanks to D unifying member 
> invocation via object and via pointer to object, this should be 
> mostly transparent to Phobos algorithms. This gets around the 
> complications with postblits / copy ctors and Phobos 
> assumptions about copyability.
>
> 	NonCopyableRange r = ...;
> 	auto rp = &r;
> 	result = rp.map!(...).filter!(...).joiner; // etc.
>
>
> T

Somehow this trick doesn't work with fold:

struct A {
     bool empty = false;
     int count = 0;
     int front = 1;
     void popFront() {
         count++; if (count > 100) empty = true;
     }
}
void main() {
     import std.range, std.stdio, std.array, std.algorithm;
     A range;
     auto x = (&range).fold!"a+b"(4); // doesn't work
     // auto x = range.fold!"a+b"(4); // works
     writeln(x);
     writeln(range.count);
}


More information about the Digitalmars-d mailing list