On Saturday, 2 April 2022 at 14:49:15 UTC, Vijay Nayar wrote:
On Saturday, 2 April 2022 at 14:35:10 UTC, Vijay Nayar wrote:
The `tryMatch` method fails to compile, and instead I get the following error:
```d
/dlang/dmd/linux/bin64/../../src/phobos/std/sumtype.d(2004): Error: static assert: "`handlers[0]` of type `int function(ref ubyte[] _1, ref ubyte[] _2) pure nothrow @nogc @safe` never matches"
```

Through sheer trial and error, I discovered that changing the handler arguments from `ref ubyte[]` to `const ref ubyte[]` the error goes away. However, I did not find any information in the documentation or code that made this requirement clear. It was basically a guess based on the fact that `string` has no trouble but `ubyte[]` did, and string is basically just `immutable(char[])`.

So far, I'm finding that learning to use `SumType` is significantly more cryptic than `Variant`, by a large margin. I'll still give it a shot of course, because I want to get past this problem.

Try this:

```d
import std.sumtype;
import std.algorithm : cmp;

alias VarType = SumType!(double, ubyte[]);


int opCmp(const ref VarType v1, const ref VarType v2) {
        //you need all combinations of types:
        static int impl(A, B)(auto ref A a, auto ref B b){
                // (double, ubyte[]) or  (ubyte[], double):
                static if(!is(immutable A == immutable B))
                        assert(0, "type missmatch");
                // (ubyte[], ubyte[]):
                else static if(is(immutable A == immutable ubyte[]))
                        return cmp(a, b);
                // (double, double):
                else
                        return (a < b) ? (-1) : (a < b ? 1 : 0);
    }
        return tryMatch!impl(v1, v2);
}

void main(){
        VarType b1 = cast(ubyte[]) [0x01, 0x02, 0x03];
        VarType b2 = cast(ubyte[]) [0x01, 0x02, 0x04];
assert(opCmp(b1, b2) == -1); //operator overloading work only if opCmp is method.
}
```

Reply via email to