I am building a custom BDD class to store different types of data (e.g., long
, char*
, double
, …) for my program.
In order to store the data, I need a struct for each table, like this:
struct MYSTRUCT0
{
char variable0[10];
char variable1[70];
};
struct MYSTRUCT1
{
long variable0;
long variable1;
char variable2[6];
double variable3;
};
But it's much work each time I need a new table, because I need to write a function to save each table in a file, to read it, etc. Worse, it's not really object-oriented.
So my question is, is there a way to "browse" the struct to simplify my code? Something like this:
for(int v=0; v<arraysize; v++)
for(int i=0; i<MYSTRUC0.length; i++)
{
if (MYSTRUCT.getvar(i).type == long)
DoSomethingForLong(myarray(v).getval(i));
if (MYSTRUCT.getvar(i).type == char*)
DoSomethingForCharPtr(myarray(v).getval(i));
}
I know it's possible for code like this to work directly in C++. I just use it to illustrate what I mean.
Below code is just an example of how you can make your own "variable-type-aware" struct that maybe what you want:
#include <vector>
enum MyTypes
{
LONG,
CHARPTR,
DOUBLE,
} myTypes;
struct MyStruct
{
MyStruct(long longVar)
{
variable.longVar = longVar;
whichType = LONG;
}
MyStruct(char* charPtr)
{
variable.charPtr = charPtr;
whichType = CHARPTR;
}
MyStruct(double var)
{
variable.var = var;
whichType = DOUBLE;
}
~MyStruct()
{
}
MyTypes whichType;
union {
long longVar;
char* charPtr;
double var;
} variable;
};
void DoSomethingForLong(MyStruct* doubleStruct)
{
/*Do something specific to long*/
};
void DoSomethingForCharPtr(MyStruct* doubleStruct)
{
/*Do something specific to char pointer*/
};
void DoSomethingForDouble(MyStruct* doubleStruct)
{
/*Do something specific to double*/
};
int main()
{
std::vector<MyStruct*> myVec;
// add a struct with long variable
long longVar = 2000000000;
MyStruct* myLongStruct = new MyStruct(longVar);
myVec.push_back(myLongStruct);
// add a struct with char pointer
char* charArray = new char[1000];
MyStruct* myCharPtrStruct = new MyStruct(charArray);
myVec.push_back(myCharPtrStruct);
// add a struct with double variable
double doubleVar = 200.200;
MyStruct* myDoubleStruct = new MyStruct(doubleVar);
myVec.push_back(myDoubleStruct);
for (int i = 0; i < myVec.size(); ++i)
{
MyStruct* tempStruct = myVec[i];
if (tempStruct->whichType == LONG)
{
DoSomethingForLong(tempStruct);
}
else if (tempStruct->whichType == CHARPTR)
{
DoSomethingForCharPtr(tempStruct);
}
else if (tempStruct->whichType == DOUBLE)
{
DoSomethingForDouble(tempStruct);
}
}
if (myLongStruct)
{
delete myLongStruct;
myLongStruct = nullptr;
}
if (myCharPtrStruct)
{
if (charArray)
{
delete[] charArray;
charArray = nullptr;
}
delete myCharPtrStruct;
myCharPtrStruct = nullptr;
}
if (myDoubleStruct)
{
delete myDoubleStruct;
myDoubleStruct = nullptr;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With