mercredi 18 mai 2016

Iterate through struct by variable name

Before you comment telling me to use an array or vector, or any form of container instead, it is a hard truth that I cannot. I know, this would be solved with an array, and any solution otherwise is pretty "hacky". I would love to use a container, but I absolutely cannot.

I am a mid-level developer at a very large corporation, and we are using a company-wide library for sending data over ethernet. There are various reasons for why it cannot support arrays/vectors, and instead, uses structs of POD (Plain Old Data - chars, floats, ints, bools). I start with an array of floats that I must use to fill a struct with the same number of floats. Since the purpose of this library is to send messages over ethernet, I only need to do the iteration twice - once on the send and one on the receive. All other times, this data is stored as an array. I know - I should be serializing the arrays and sending them as is, but I repeat - I absolutely cannot.

I have a float[1024], and must iterate through the array and fill the following struct:

struct pseudovector
{
    float data1;
    float data2;
    float data3;
    ...
    float data1024;
}

I am already generating this struct with BOOST_PP_REPEAT and BOOST_PP_SEQ_FOR_EACH_I so that I do not have to write out all 1024 floats, and it increases maintainability/extensibility.

In the same fashion, I have tried iterating through the struct via pre-compiler ## concatination (http://ift.tt/1Tkxxhs), but as this is done at pre-compiler time, it cannot be used for run-time getting/setting.

I have looked at implementing reflection such as How can I add reflection to a C++ application? and Ponder Library, but both approaches requires you to explicitly write out each item that can be reflected upon. In that case, I might as well just create a std::map<string, float> and iterate in a for loop via string/integer concatenation:

for(i=0;i<1024;i++)
{
    array[i] = map.get(std::string("data")+(i+1))
}

Can anyone recommend a cleaner solution that does not require me to write out in excess of 1024 lines of code? Your help is appreciated!

Again, I repeat - I absolutely cannot use an array/vector of any sort.





Aucun commentaire:

Enregistrer un commentaire