jepugs jepugs - 1 month ago 6x
C++ Question

Returning a mutable value in C++11

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;
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.


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]; }
//                               ^^^^