Using multiple mixin templates to implement operator overloading

Paul Backus snarwin at gmail.com
Sat Dec 12 18:14:31 UTC 2020


On Saturday, 12 December 2020 at 17:36:57 UTC, Tobias Pankrath 
wrote:
> I want to wrap e.g. an int and implement basic arithmetic. In 
> the provided example [1] I use  two mixin templates to 
> separately implement scaling (multiplication with int/double) 
> and addition and subtraction with the type itself.
>
> In the end I want to have several distinct wrappers and allow 
> specific operations between them and int / double. It's 
> important that the return values are typed correctly, otherwise 
> I could use std.typecons.Proxy.
>
> My problem is that both overloads of opBinary work, but not at 
> the same time. As soon as I mixin both templates, they stop to 
> work. If I just paste the implementation into the body of 
> WrapInt, they work both at the same time though.
>
> Could someone explain the mechanics behind it?
>
> Thanks!
>
> [1] https://run.dlang.io/is/WbG987

Functions from different mixin templates can't overload each 
other. The reason for this is that, when you mix in a mixin 
template, it does not *actually* add the declarations inside it 
to a current scope: instead, it adds them to a new scope, and 
then (essentially) "imports" them into the current scope.

IMO this is one of the stupider design decisions in D, but it's 
unlikely it will ever be fixed. The easiest workaround is to use 
string mixins instead, which work the way you'd expect them to.


More information about the Digitalmars-d-learn mailing list