+ 3
(C++) auto create object / variable
i want to create variable / object with a specific pattern. example in python, i can write something like: num = 0 for (i in range(10)): auto = "var%d = %d" %(num, num) exec(auto) num+=1 so i have 10 variable now. unfortunately, c++ doesnt have a function like enum or exec. any idea? im stuck here.
5 Answers
+ 4
You can do it with arrays, but the variable name do not really change
You can allocate memory so that you have more space (like more integers) usable during runtime
+ 4
you can overload string operator '%', but the problem will reside in the right part of the code.
If num is not a primitive type (can be a wrapper of a primitive type), you'll have to override the ',' operator to store all the variables (maybe return a std::tuple) then use it with the operator '%' you did with the tuple you used. If you want to keep track of num so that it can be changed, use references
+ 4
I read back the question, and indeed I made a mistake. You can't create variable names at runtime (you can though at compile time)
+ 1
@baptiste
im not understand. your point is, i need to overload string operator?
0
yeah. what i mean is create variable at runtime. i hope i can find the answer :)