operator overloading outside the type

David O david at errol.org.uk
Sat Oct 25 09:41:33 UTC 2025


On Wednesday, 2 April 2025 at 12:19:44 UTC, Dukc wrote:
> On Tuesday, 1 April 2025 at 13:06:21 UTC, Mengu wrote:
>> Wny can't we just treat operators as functions or vice versa? 
>> Haskell does this perfectly:
>>
>> ```haskell
>> ghci> :i (+)
>> type Num :: * -> Constraint
>> class Num a where
>>   (+) :: a -> a -> a
>>   ...
>>         -- Defined in ‘GHC.Num’
>> infixl 6 +
>> ghci> 1 + 1
>> 2
>> ghci> (+) 1 1
>> 2
>> ```
>
> Well, user-definable order of evaluation would mean that you 
> can't figure out order of evaluation in expressions anymore at 
> the parsing phase, since `infix`/`infixl`/`infixr` operators 
> couldn't be processed before the semantic phase (especially if 
> they are mixed in!). Non-expression syntaxes wouldn't be 
> affected, though, and you could still always figure out what's 
> part of an expression and what's not.
>
> But we could have operators to be just syntactic sugar over 
> functions, just with a fixed order of evaluation. For user 
> defined types, this is almost how it already works after all. 
> `a + b` is the same as `a.opBinary!"+"(b)`, or 
> `b.opBinaryRight!"+"(a)`. We'd simply have to allow those to 
> call module-scope functions as per normal UFCS rules, and maybe 
> define members/`object.d` intrinsic functions so that 
> `5.opBinary!"+"(5)` would work.

I have a generic struct

struct BaseUnits(string type)
{
...
}

I can define lengths:

enum  m = BaseUnits!"m"(1.0);
enum km = BaseUnits!"m"(1.0E3);

and areas:

enum  m2 = BaseUnits!"m2"(1.0);
enum km2 = BaseUnits!"m2"(1.0E6);

I can scale them and add them:

auto a = 7*m;
auto a = m + km;

Now I want to make a volume:

BaseUnits!"m3" b = m * m2;

But I need a free standing operator overload for this!


More information about the Digitalmars-d mailing list