Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subscript (" [ ] ")operator gives strange errors

I am getting some strange behaviour from visual studio, regarding the following code snippet, The error list shows several instances of E0349: no operator"[]" matches these operands.

Intellisense seems to be implying a type mismatch, but as you will see in the code, there is no type mismatch.

To begin, I have defined a Vec4 struct for the purposes of making a mat4: (I have only included the pertinent functions)

struct Vec4f
{
    union
    {
        struct { float x, y, z, w; };
        struct { float r, g, b, a; };
    };
    // copy constructor
    Vec4f(Vec4f const & v) :
        x(v.x),
        y(v.y),
        z(v.z),
        w(v.w)
    {

    }
    // Operators
    float & operator[](int index)
    {
        assert(index > -1 && index < 4);
        return (&x)[index];
    }

    Vec4f & operator=(Vec4f const & v)
    {
        // If I use: "this->x = v[0];" as above, E0349
        this->x = v.x;
        this->y = v.y;
        this->z = v.z;
        this->w = v.w;
        return *this;
    }    
}

Using the above Vec4 class, I have created a 4x4 matrix:

struct Mat4f
{
    //storage for matrix values
    Vec4f value[4];

    //copy constructor
    Mat4f(const Mat4f& m)
    {
        value[0] = m[0]; // calling m[0] causes E0349
        value[1] = m[1];
        value[2] = m[2];
        value[2] = m[3];
    }

    inline Vec4f & operator[](const int index)
    {
        assert(index > -1 && index < 4);
        return this->value[index];
    }
}

When any of the "[]" operators are called, I end up with this E0349 error, and I do not understand the problem. Oddly, the file compiles just fine. I have tried deleting the hidden ".suo" file as suggested in an answer to a different question, but to no avail. I would appreciate this explained to me.

like image 426
Ian Young Avatar asked Aug 23 '26 00:08

Ian Young


1 Answers

Mat4f::operator[] is a non-const member function, which can't be called on the argument m of Mat4f::Mat4f, it's declared as const & Mat4f.

You could add another const overloading, which could be called on constants. e.g.

inline Vec4f const & operator[](const int index) const
//           ~~~~~                               ~~~~~
{
    assert(-1 < index && index < 4); // As @Someprogrammerdude commented, assert(-1 < index < 4) doesn't do what you expect
    return this->value[index];
}
like image 63
songyuanyao Avatar answered Aug 25 '26 15:08

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!