Trying to use a template class with ranges

mark mark at qtrac.eu
Thu Feb 6 16:05:49 UTC 2020


On Thursday, 6 February 2020 at 15:21:46 UTC, Steven 
Schveighoffer wrote:
[snip]
> 3. You should declare constraints signifying what types are 
> valid. i.e.:
>
> class Diff(T) if (
>    isForwardRange!T // it's a forward range
>    && is(typeof(T.init.front == T.init.front)) // elements are 
> comparable
> )
>
> Might be good to put this constraint on the factory function 
> too.

I don't know how to do that syntactically. I tried the obvious 
and it wouldn't compile.

But even without that it won't compile although it is much closer 
now!

import std.range: ElementType, front, isForwardRange;

class Diff(T) if (
         isForwardRange!T && // T is a range
         is(typeof(T.init.front == T.init.front)) // Elements 
support ==
         ) {
     alias E = ElementType!T;

     T a;
     T b;
     size_t[][E] b2j;

     this(T a, T b) {
         this.a = a;
         this.b = b;
         chainB();
     }

     private final void chainB() {
         foreach (i, element; b)
             b2j[element] ~= i;
         // TODO
     }
}

auto differ(T)(T a, T b) { return Diff!T(a, b); }

unittest {
     import std.array;
     import std.stdio: writeln;

     writeln("unittest for the diffrange library.");
     auto d1 = differ("one two three four".array, "one too tree 
four".array);
     auto a = ["Tulips are yellow,", "Violets are blue,", "Agar is 
sweet,",
               "As are you."];
     auto b = ["Roses are red,", "Violets are blue,", "Sugar is 
sweet,",
               "And so are you."];
     auto d2 = differ(a, b);
}

Here's the error output:

Excluding package.d file from test due to 
https://issues.dlang.org/show_bug.cgi?id=11847
src/package.d(50,35): Error: no property opCall for type 
diffrange.Diff!(dchar[]), did you mean new Diff!(dchar[])?
src/package.d(57,21): Error: template instance 
diffrange.differ!(dchar[]) error instantiating
src/package.d(50,35): Error: no property opCall for type 
diffrange.Diff!(string[]), did you mean new Diff!(string[])?
src/package.d(62,21): Error: template instance 
diffrange.differ!(string[]) error instantiating
/home/mark/opt/bin/ldc2 failed with exit code 1.

Curiously the "Excluding package.d file" message isn't true.
Not that I mind, I just want to be able to get it going.

Thanks!

PS The line numbers don't match because I've deleted some structs 
& enums that are above the class but which aren't used yet.


More information about the Digitalmars-d-learn mailing list