assigning to a member from a struct, obtained by []

Hello
I'm trying to assign a value to a member of a struct that I called via an overloaded [] operator.

I have the following code for the struct:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
typedef struct {
	float r, g, b, a;
	float operator [](int pos)
	{
		switch (pos)
		{

		case 0:
			return r;
			break;
		case 1:
			return g;
			break;
		case 2:
			return b;
			break;
		case 3:
			return a;
			break;
		default:
			return r;
			break;
		}


	}
	
	
} MyStruct;


And what I wish to do is
1
2
3
4

 MyStruct a;

 a[0] = 0.5;


Is it possible with a struct? I have no idea how to express this to search engines so I haven't been able to find anything about it.

If this is not possible with a struct, is there a way to define something that can do all the following things:
1
2
3
4
5
6
7
SomeStruct test = {0.5, 0.5, 0.5, 1}; 

test.g = 1.0;
test[0] = 0.0; // test[0] would be equivalent to calling test.r

float somevalue = test[3]; // test[3] would be equivalent to calling test.a


I hope I've been sufficiently clear
Thanks in advance!
Yes, it is. You need to return a reference to the variable. Also, it is generally prefer to throw an out of range error for the operator[], so as to signal that you are accessing an illegal value. Here is an example:
1
2
3
4
5
6
7
8
9
10
11
12
struct MyStruct {
    float r, g, b, a;
    float& operator[] (size_t pos) {
        switch (pos) {
            case 0: return a;
            case 1: return g;
            case 2: return b;
            case 3: return a;
        }
        throw std::out_of_range("MyStruct operator[]");
    }
};
Thank you so much!!
works like a charm

I had no idea how to express it!
Last edited on
Topic archived. No new replies allowed.