logical operands on strings
    TheFlyingFiddle 
    kurtyan at student.chalmers.se
       
    Sun Jan 12 11:12:12 PST 2014
    
    
  
On Sunday, 12 January 2014 at 18:37:40 UTC, Erik van Velzen wrote:
> On Sunday, 12 January 2014 at 18:28:38 UTC, Meta wrote:
>>
>> 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.
>
> How would I do that without rewriting an entire string class?
Well something like this.
struct MyString
{
    string value;
    alias value this;
    auto opBinary(string op)(string rhs) if( op == "^" )
    {
       string result;
       foreach(i; 0 .. min(value.length, rhs.length))
           result ~= value[i] ^ rhs[i];
       return MyString(result);
    }
}
auto mstr(string s)
{
    return MyString(s);
}
auto s   = "Hello";
auto s2  = "World";
auto res = s.mstr ^ s2;
or
string res = s.mstr ^ s2; //If you want the result to be a string.
While this works it's not that much better then the simple:
auto s = "Hello";
auto s2 = "World";
auto res = s.xor(s2);
> It seems I can't even inherit from string.
In D a string is not a class its just an immutable array (slice) 
of char.
alias string = immutable(char[]);
    
    
More information about the Digitalmars-d-learn
mailing list