Difference between range `save` and copy constructor

uranuz neuranuz at gmail.com
Sun Feb 16 09:21:30 UTC 2020


> Actually, as I understand it, the main reason that save was 
> introduced was so that classes could be forward ranges

I have use of ranges as a classes in my code that rely on classes 
and polymorthism, but it's usually an InputRange that implements 
Phobos interface:
https://dlang.org/phobos/std_range_interfaces.html#.InputRange

I have virtual opSlice operator that returns InputRange. And 
sometimes implementation of range is very different. So it's 
difficult to write one range as a struct. I have a pattern in my 
code that looks like the following:

interface IContainer
{
    InputRange opSlice();
}

class MyContainer1: IContainer
{
    class Range1: InputRange {
       //... one implementation
    }
    override InputRange opSlice() {
        return new Range1(this);
    }
}

class MyContainer2: IContainer
{
    class Range2: InputRange {
       //... another implementation
    }
    override InputRange opSlice() {
        return new Range2(this);
    }
}

In this example I need a range to be a class, but not a struct.

Another problemme is that `copy contructor` is defined only for 
structs, but not classes. For the class that uses another class 
instance of the `same` type to initialize from it would be a 
regular constructor with parameter.
A copy constructor in struct semantics requires that the source 
would be actually `the same` type. But for classes source could 
be instance of another class that is inherited from current 
class. And we cannot prove statically that it's actually the same 
type.
And also if we talk about range interface constructor cannot be a 
part of it. So we cannot add `copy contructor` (if we would have 
it for class) to interface and check for it's presence in generic 
code. So here we have this workaround with `save` method...
I don't like that primitive concept has two ways to do the same 
thing. And it's unclear what is the primary way of doing this 
(copy constructor or save). It introduce the situation when half 
of the code would require range being copyable, but another part 
would require it to to have a save method. Not the situation is 
that there are a lot of algorothms in Phobos that are not working 
with ranges that have disabled postblit, but have `save` method 
that could be used to make a copy.
Still I want to be able to create ranges as classes...


More information about the Digitalmars-d-learn mailing list