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[]");
}
};