Question

I was wondering about having a method return an r-value. Specifically, I was wondering if there was a way to do this with an overloaded operator. I have this code:

struct vec4 {
    float x;
    float y;
    float z;
    float w;
    ...
    inline float operator [] (int i)
    {
            switch (i) {
            case 0:
                    return this->x;
            case 1:
                    return this->y;
            case 2:
                    return this->z;
            case 3:
                    return this->w;
            default:
                    exit(1);
                    return 0;
            }
    }
};

How can I change this so that I could use something to the effect of

vec4 v;
...
v[2] = 5.0f;

I've hear about rvalue references in C++11, and could they be a potential solution?

EDIT: I found a way to put in my actual code.

Was it helpful?

Solution

No C++11 is needed for this. Just have:

float & operator[](std::size_t i) { return data[i]; }

Now you can say v[2] = 5; and all is well.

If you wanted, you could add a constant overload that doesn't use references and which can be used for reading the value.

float operator[](std::size_t i) const { return data[i]; }

The only time you might consider rvalue member function qualifiers is if you wanted to allow assigning to a temporary member:

vec4{}[2] = 5;

In that case, you still return a lvalue reference, but you must qualify the member function:

float & operator[](std::size_t i) && { return data[i]; }
//                               ^^^^

OTHER TIPS

You can simply use:

float& operator [] (int index)
{
    return data [i];
}

This allows you to write v[2] = 5.0f; and it will work as expected. No need for r-value references here.

You should also add a const-overload to retrieve the value, like this:

float operator [] (int index) const
{
    return data [i];
}

This will allow you to write code like this: const vec4 v; float x = v[1];.

For what you want to accomplish, you apparently want to return an lvalue, not an rvalue. That's actually pretty easy:

float &operator[](size_t i) { return data[i]; }

Note that when you're defining the function inside the class definition, inline is redundant -- defining the function inside the class definition makes it inline by default.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top