C ++ variable variable names

Problem : I've been looking here for some time trying to find a way to sort out the variables, to name a few like variable_1

, variable_2

...., variable_n

. In principle, I ask, is there a way to do this using the cycle to achieve variable_i

, or more particularly, in my case functionName_i

.

What I need : I am trying to code an array of objects to call various functions that are sequentially named and parallel to the array of objects (ie: obj [i] -> callback_i ())

What do I know . Obviously the answer here (if it's just variables) uses an array or a vector. I know that C ++ is not dynamic and cannot create variables at runtime. However, this is not what I need here. I just need to concatenate the function names sequentially if possible.

Possible workarounds . Everything I think of goes back to creating an array / vector of function pointers. I could get it to work eventually if I really have no options, but I just thought I should ask out of curiosity.

Clear the question . Is there a way to loop over sequentially named functions using an int variable i

as part of the function names?

Thank!

+3


source to share


1 answer


Not.

C ++ usually does not store type name or variable information at runtime; if so, it is not portable ( typeid()

not dependent on different compilers), or it just isn't possible. You cannot refer to a variable name at runtime, unless you make some kind of system to do so, or use debug information that is not a standard C ++ function.

This type of road reflection is more suitable for higher level languages. C ++, as a lower-level language, removes the sugar and simply says no.



You can do this type of thing in C ++ if you create a naming system, but in a generic way it would also require variations, NULL/Maybe

idiom version , attributes, validations, a lot of debugging, and you can do it all if you want, but here you can switch to another language that already has the answer you are looking for and link C ++ with it.

Alternatively use a matrix or array of functions. Then iterate over the index.

+3


source







All Articles