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?
It seems I can't even inherit from string.
Forgive me for making the comparison, but I believe in C++ i
can simply implement this function and be done with it:
string operator^(string lhs, string rhs);
global operator overloads aren't allowed in D. For your
particular problem I would construct a wrapper around string
using psuedo-inheritance via 'alias this':
struct MyString
{
string nativeStr;
alias nativeStr this;
auto opBinary(string op)(string rhs)
if(op == "^")
{
return xor(nativeStr, rhs);
}
void opOpBinary(string op)(string rhs)
if(op == "^")
{
nativeStr = xor(nativeStr, rhs);
}
}
All normal string operations on a MyString will be applied to
nativeStr thanks to alias this, except the ^ and ^= whch are
intercepted by the opBinary and opOpBinary methods in MyString.
The ^= could be more efficient by working in-place.
Also, you should pre-allocate the return string in xor as it's a
lot quicker than doing repeated append operations.