operator overloading outside the type

Mengu mengukagan at gmail.com
Tue Apr 1 13:06:21 UTC 2025


On Sunday, 30 March 2025 at 03:11:48 UTC, Walter Bright wrote:
> On 3/29/2025 12:24 PM, sfp wrote:
>> [...]
>
> If an operator overload can only be defined in the definition 
> of the type, then people know where to look for it.
>
>
>> [...]
>
> From just reading code, an overloaded operator will not be 
> apparent.
>
> I recall when David Abrahams wrote a C++ regex package that 
> used operator overloading for regex operations. Seeing it in 
> action, it was surprisingly difficult to figure from reading 
> the code which was C++ code and which was regex code.
>
> It took maybe 10 years for the C++ community to reach the 
> conclusion that iostreams was operator overloading abuse and a 
> bad idea.
>
>
>> [...]
>
> I have not seen your code and so cannot form an opinion about 
> it. No doubt it is possible to write good code with 
> freestanding operator overloads. But the history of it is not 
> encouraging.
>
> I've often had the fortune (or misfortune!) of having to work 
> on code I haven't touched for 5 years or more, and it being 
> quite baffling. Once I figure it out again, I wind up redoing 
> it for better clarity. Sometimes that meant making the code 
> less clever.

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
```


More information about the Digitalmars-d mailing list