Dynamically enumerating the members of a C++ struct

In C++ there is a struct with the following structure:

typedef struct myStruct
{
    string s_date;
    float fA;
    float fB;
    float fC;
    .....
    float fZ;
} myData;

After some computations on the values of the struct members are inserted into a database table:

myData ind;
string sqlInsert = "INSERT INTO calculations (date, A, B, C, ..., Z) 
VALUES ('"+ind.s_date+"','"+ftostr(ind.fA)+"','"+ftostr(ind.fB)+"','"+ftostr(ind.fC)+"','"+ ... +"','"+ftostr(ind.fZ)+"')";

Given that the members of the struct can change, as well as currently close to 100 members, we are looking for a way to loop over the members in a dynamic fashion, without having to spell out each member individually.

Therefore the question is, is there a way to loop over the struct members so that the SQL that comes after the VALUES clause is updated based on however many struct members there are?

You can't do that sadly. What I usually see done when this is needed is one of two things:

  • Some sort of dynamic structure, like a map or hash or list, without predefined contents.

OR

  • Use a script to build the structure out of some sort of data file, and also build an array which describes its contents.

Thank you for your response. Do you have examples of C++ maps and/or C++ hash lists? And what exactly do you mean by "without predefined contents"?

Instead of having one big structure with hardcoded members like x.ytypeofvalue, have a container holding many structures with two members, name and value. You can store this in many kinds of data structures like lists, maps, vectors, arrays, most anything iterable.

#include <map>
#include <string>

#define foreach(var, container)                 \
                for(typeof((container).begin()) var = (container).begin(); \
                var != (container).end(); \
                ++var)

int main(void)
{
        std::map<std::string,std::string> mydata;

        mydata["a"]="b";
        mydata["c"]="d";

        foreach(x, mydata)
        {
                cout << (*x).first <<" "<<(*x).second<<"\b";
        }
}

Was not aware of this structure, but have read up more on it in the meantime. Thank you for your guidance.