Template mixin + operator overloading question

Boyan Lazov boyan.lazov at gmail.com
Fri Oct 11 12:45:59 UTC 2019


Hello,

I seem to have a problem when I use a template mixin and then try 
to overload operators both in the mixin and in a struct from 
where it's instantiated.
So the idea is that I have a few operators defined in the mixin, 
then a few more in the struct, and I want to forward all 
operations not explicitly defined in the struct to the ones in 
the mixin (and I don't want to do alias this for a variety of 
unrelated reasons).

Basically the simplest code that gives me problems is:

import std.stdio;

mixin template Impl(T) {
     T v;
     int opBinary(string s: "+")(T other) {
         writeln("Single +");
         return 0;
     }
     int opBinary(string s: "+")(T[] other) {
         writeln("Array +");
         return 0;
     }
}

struct Pt {
     mixin Impl!float impl;

     int opBinary(string s: "*")(float other) {
         writeln("Single *");
         return 0;
     }

     int opBinary(string s, T)(T v) {
         //Pt already has opBinary defined, so the operators in 
the mixin not visible
         //Thought that delegating to the mixin should be done 
this way
         writeln("Delegate ", s);
         return impl.opBinary!(s)(v);
     }
}


void main() {
     Pt pt;
     int r = pt + [1f, 2f];
     writeln("R: ", r);
}

This results in an infinite loop though. Seems like 
Pt.opBinary!("+", float[]) is called over and over. Which is a 
bit un-intuitive to me - I'm not sure why calling 
impl.opBinary!(s) can result in endless recursion.

The problem appears only when I have 2 operators in the mixin 
that I try to forward to - e.g. the two overloads of "+" in this 
case. If I have just 1, it works ok, if I have none, the error 
message is helpful.

Any ideas what I'm doing wrong?
Thanks!


More information about the Digitalmars-d-learn mailing list