logical operands on strings

Meta jared771 at gmail.com
Sun Jan 12 10:28:36 PST 2014


On Sunday, 12 January 2014 at 18:21:06 UTC, Erik van Velzen wrote:
> I would like to do this:
>
>     string one = x"315c4eeaa8b5f8aaf9174145bf43e1784b";
>     string two = x"c29398f5f3251a0d47e503c66e935de81230b59b7a";
>     string three = one ^ two;
>
>
> The closests I've been able to get is:
>
>     string three = xor(one, two);
>
>     string xor(string one, string two) {
>         int len = min(one.length, two.length);
>         string result;
>         for(int i=0; i<len; i++) {
>             result ~= one[i] ^ two[i];
>         }
>         return cast(string)result;
>     }
>
> Question 1: is there a more elegant way to implement the 
> function xor? (foreach-ish or std.algorithm)
>
>
> Then I tried to add operator overloading:
>
>     string opBinary(string op)(string lhs, string rhs) {
>         static if( op == "^" )
>             return xor(lhs, rhs);
>         else static assert(false, "operator not possible");
>     }
>
> But it doesn't invoke this function.
>
> Question 2: how would I implement "^" for strings?

It looks like your opBinary on strings is an attempt at globally 
overriding the XOR operator. I'm almost 100% sure this won't work 
in D. All operator overloads have to be part of a class or struct.


More information about the Digitalmars-d-learn mailing list