Reputation: 411
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:
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!
Upvotes: 1
Views: 119
Reputation: 363
you should add a selection method in Assumption class, taking the key as input.
Upvotes: 0
Reputation: 47790
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.
Upvotes: 0
Reputation: 96241
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.
Upvotes: 2