Referencing variables in a structure / C++
- by user1628622
Below, I provided a minimal example of code I created. I managed to get this code working, but I'm not sure if the practice being employed is sound. In essence, what I am trying to do is have the 'Parameter' class reference select elements in the 'States' class, so variables in States can be changed via Parameters.
Questions I have: is the approach taken OK? If not, is there a better way to achieve what I am aiming for?
Example code:
struct VAR_TYPE{
public:
bool is_fixed; // If is_fixed = true, then variable is a parameter
double value; // Numerical value
std::string name; // Description of variable (to identify it by name)
};
struct NODE{
public:
VAR_TYPE X, Y, Z;
/* VAR_TYPE is a structure of primitive types */
};
class States{
private:
std::vector <NODE_ptr> node; // shared ptr to struct NODE
std::vector <PROP_DICTIONARY_ptr> property; // CAN NOT be part of Parameter
std::vector <ELEMENT_ptr> element; // CAN NOT be part of Parameter
public:
/* ect */
void set_X_reference ( Parameter &T , int i ) { T.push_var( &node[i]->X ); }
void set_Y_reference ( Parameter &T , int i ) { T.push_var( &node[i]->Y ); }
void set_Z_reference ( Parameter &T , int i ) { T.push_var( &node[i]->Z ); }
bool get_node_bool_X( int i ) { return node[i]->X.is_fixed; }
// repeat for Y and Z
};
class Parameter{
private:
std::vector <VAR_TYPE*> var;
public:
/* ect */
};
int main(){
States S;
Parameter P;
/* Here I initialize and set S, and do other stuff */
// Now I assign components in States to Parameters
for(int n=0 ; n<S.size_of_nodes() ; n++ ){
if ( S.get_node_bool_X(n)==true ){
S.set_X_reference ( P , n );
};
// repeat if statement for Y and Z
};
/* Now P points selected to data in S, and I can
* modify the contents of S through P
*/
return 0;
};
Update
The reason this issue cropped up is I am working with Fortran legacy code. To sum up this Fotran code - it's a numerical simulation of a flight vehicle. This code has a fairly rigid procedural framework one must work within, which comes with a pre-defined list of allowable Fortran types. The Fortran glue code can create an instance of a C++ object (in actuality, a reference from the perspective of Fortran), but is not aware what is contained in it (other means are used to extract C++ data into Fortran).
The problem that I encountered is when a C++ module is dynamically linked to the Fortran glue code, C++ objects have to be initialized each instance the C++ code is called. This happens by virtue of how the Fortran template is defined.
To avoid this cycle of re-initializing objects, I plan to use 'State' as a container class. The Fortran code allows a 'State' object, which has an arbitrary definition; but I plan to use it to harness all relevant information about the model. The idea is to use the Parameters class (which is exposed and updated by the Fortran code) to update variables in States.