July 28, 2022

So, I've came to a situation where I must use mixin template for defining members overloads, like:

mixin template OverloadGen()
{
    static if(hasMethod!(typeof(this), "add", int, int))
    {
        float add(float x, float y){return x+y;}
    }
    static if(hasMethod!(typeof(this), "mul", int, int))
    {
        float mul(float x, float y){return x*y;}
    }
}

I know this example is obvious, but I'm using this for a far more complex, so I need that to work.

The current way I tried to solve that was using string mixins such as:

enum mixOverloadGen()
{
    return q{
        mixin OverloadGen __ogen__;
        static foreach(mem; __traits(allMembers, __ogen__))
        {
            mixin("alias ",mem," = __ogen__.",mem,";");
        }
    };
}

class Tester
{
    int add(int, int){return 0;}
    mixin(mixOverloadGen);
}

The problem doing that is that I can have access to __ogen__, which makes code like that valid: tester.__ogen__.add. I can't make private mixin OverloadGen __ogen__, because I won't be able to publicly access my overloads.

And doing static foreach(mem; mixin OverloadGen) is also invalid, tried with allMembers, so, this is my current solution, the other thing I could do is instead of aliasing to the mixin members, I could make them private and declare a public function inside my string mixin which calls those, which is just wasteful: increase compile time, runtime usage and code complexity.