On Sunday, 19 May 2013 at 07:32:11 UTC, matovitch wrote:
const Vertex opBinary(string op : ["+", "-"])(const ref Vertex vertex)
        {
                {
                        Vertex result = *this;
                        mixin("result" ~ op ~ "= vertex;");
                        return result;
                }
        }

        const T opBinary(string op : "*")(const ref Vertex vertex)
        {
                
                T result = 0;
                foreach(i; 0..vertex_size)
                        result += coordinate[i] * vertex.coordinate[i];
                return result;
        }

The second one is okay, but the fisrt one isn't correct. I think this kind of template specialization over a list could be great with mixins and static if/switch. What do you think ? May be there is an other way to do what I want...

I think a better syntax would be:

const Vertex opBinary(string op : "+", "-")(const ref Vertex vertex)

this will save a bit of ambiguity(`op` is a `string` specialization of `string[]`?)

At any rate, I'm not sure how useful it would be. Operator overloading code usually fit for a single operator - you usually write one for each operator:

        const Vertex opBinary(string op : "+")(const ref Vertex vertex)
        {
                Vertex result = this;
        result += vertex;
                return result;
        }
        const Vertex opBinary(string op : "-")(const ref Vertex vertex)
        {
                Vertex result = this;
        result -= vertex;
                return result;
        }

If you want to have several operators in the same method, you can afford the verbosity of:

    const Vertex opBinary(string op)(const ref Vertex vertex)
        if (__traits(compiles, mixin("this " ~ op ~ "= vertex;")))
    {
        Vertex result = *this;
        mixin("result" ~ op ~ "= vertex;");
        return result;
    }

Reply via email to