F i L
F i L

Reputation: 760

D opBinary()() overloading bug?

When I try and overload opBinary on a simple Vector struct, I get a strange and meaningless error:

struct Vector(T)
{
    T x, y;

    Vector opBinary(string op)(Vector!float vector)
    {
        return Vector (
            mixin("x" ~ op ~ "vector.x"),
            mixin("y" ~ op ~ "vector.y")
        );
    }

    Vector opBinary(string op)(Vector!double vector)
    {
        return Vector (
            mixin("x" ~ op ~ "vector.x"),
            mixin("y" ~ op ~ "vector.y")
        );
    }
}

void main()
{
    auto dVec = Vector!double();
    auto fVec = Vector!float();

    auto aVec = dVec + fVec; // Adding this line causes error (see below)
}

The error I get is simply: "opBinary(string op)". No line numbers, nothing. Which obviously doesn't give me a whole lot to go on. Is there another way to handle this situation? Is this a known bug?

I'm using DMD 2.057 on Windows 7. Haven't tested on Linux yet.

[EDIT] cleaned the code up a bit for readability.

Upvotes: 2

Views: 196

Answers (1)

jA_cOp
jA_cOp

Reputation: 3305

The full error is:

main.d(27): Error: template main.Vector!(double).Vector.opBinary(string op) opBinary(string op) matches more than one template declaration, main.d(5):opBinary(string op) and main.d(13):opBinary(string op)

VisualD fails to parse it, causing the error you see. Are you using VisualD?

The code works if you change it to something like:

struct Vector(T)
{
    T x, y;

    Vector opBinary(string op, U)(Vector!U vector) if(is(typeof(mixin("x" ~ op ~ "vector.x")) : T))
    {
        return Vector(
            mixin("x" ~ op ~ "vector.x"),
            mixin("y" ~ op ~ "vector.y")
        );
    }
}

Upvotes: 5

Related Questions