Custom type creation guidelines

rumbu via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jan 6 10:38:50 PST 2016


Let's suppose that I want to implement a custom arithmetic type. 
Looking through phobos at Complex, BigInt, HalfFloat, Variant, 
etc, there is no consistent or idiomatic way to implement various 
operators or functions on custom types.

1) Regarding unary operator overloading, what's the best way to 
implement them?

auto ref opUnary(string op)() if (op == "+") { ... }
auto ref opUnary(string op : "+")() if (op == "+") { ... }
auto ref opUnary(string op)() { static if (op == "+") { } else 
... }

2) Regarding binary operator overloading, question 1 apply also, 
but there is more: what's the best signature?

ref T opBinary(string op, T)(auto const ref T rhs) { ... }
inout(T) opBinary(string op, T)(inout(T) rhs) { ... }
ref T opBinary(string op, T)(T rhs) { ... }

3) Regarding comparison operators:
- is there a way to have the same result for != and == (similar 
to float nans)
- is there a way to return the same result for <, <=, >=, > 
(similar to float nans)
- is there a way to overload float comparison operators?

4) regarding casting:
- we have opCast(T) to convert my custom type to type T. Is there 
any method to overload the casting operation from a built in 
type, e.g. cast(MyType)(int)?

5) Any other guidelines?

Thanks.



More information about the Digitalmars-d-learn mailing list