Question

I need to call a member of a defined (public) class through a local variable, and I am wondering how I can do so. My problem is that which variable to call in the class is dependent upon a series of values, so I really need to use a variable to call the member rather than explicity typing it's name. For example:

I have class Assumptions, with many member variables (all of the ones of interest are type double). So let's say I have five potential variables I want to call within Assumptions, but only one of them:

  1. VariableStem_One
  2. VariableStem_Two
  3. VariableStem_Three
  4. VariableStem_Four
  5. VariableStem_Five

My code currently generates a string whose contents are equal to one of the five terms above - now I just need to call that member variable - can I do so indirectly? So I have one variable called "VariableKey" whose contents are equal to one of the five variables above - I want to make the following call:

Assumptions.VariableKey

But have the VariableKey interpretated as an indirect reference.

This is also an abstraction/simplification of my real problem - the number of possible values is more like 75, so I want to avoid coding out each variable individual if possible.

Thanks in advance!

Was it helpful?

Solution

You can't do that directly in C++. A more normal approach is to have an enumeration that indicates which variable to use, and set that. Then you have an array/vector of values, and the enumerator acts as an index into that container.

You could also create a map that maps the strings to a particular value, but that may add additional overhead.

OTHER TIPS

What you're trying to do is called "reflection", and C++ doesn't have native support for it; you could look at adding it via library, but it'd be easier to just put your "Stem" member variables into a map of string to double instead.

you should add a selection method in Assumption class, taking the key as input.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top