For performance concern, I would like to access some attributes of an existing c++ struct like an array. Here is the type of structure I have:
struct MyStruct {
Class1 c1;
Class2 c2;
MyClass myFirstAttribute, mySecondAttribute, /* ... */, myLastAttribute;
Class3 c3;
Class4 c4;
};
My goal would be to access the attributes of type MyClass
as if they were an
array such as:
struct MyStruct {
Class1 c1;
Class2 c2;
MyClass myArray[20];
Class3 c3;
Class4 c4;
};
The class MyClass only contains 1 member (a double
). So far, I
wrote the following function and it seems to work, but I am wondering if I am not just lucky that the attributes are aligned as expected:
MyClass& accessElement(struct MyStruct &s, int index)
{
MyClass *myArray = &s.myFirstAttribute;
return myArray[index];
}
Reason
Please note that this is only temporary, I know it is better to directly use an array but it needs quite a few changes, but I need the change to be transparent as I don't manage all the code using this struct. Also, the reason behind the change is for performance as the function was previously implemented using a switch statement, and compiled as a if - then - else statement. I am compiling using gcc 4.3 with -std=c++98 and -O2 options among others.
Bonus
I also tried several other tricks, but it didn't work as I am playing with a very big and complicated code, such as:
- Add the array as an attribute and change the attributes to references pointing to the the corresponding index of the array. This didn't work as it needs the copy constructor somewhere in the code and I needed to implement it, which is very fastidious (the struct is much more complicated).
- Use a define macro to automatically replace all strings with the name of the attributes I want to replace by the corresponding array with index (see below). This didn't work as some variables in another part of the code have the same name than the attributes.
Using define:
#define myFirstAttribute myArray[0]
#define mySecondAttribute myArray[1]
#define myLastAttribute myArray[20]
Qestions
Any other ideas? Or is there any way I could make my hack safer to ensure it compiles as expected?
Edit
As suggested in this post (thank you @Thomas Matthews for the link), a lookup table would be better, however you pay the cost of the indirection (same as virtual functions I think). I am wondering if something like that would be legit:
struct MyStruct {
Class1 c1;
Class2 c2;
union {
struct {
MyClass myFirstAttribute, mySecondAttribute, /* ... */, myLastAttribute;
};
MyClass myArray[];
};
Class3 c3;
Class4 c4;
};
This seems to work, and is not suggested in the other post. Do I need to pack the anonymous struct? Any suggestion?