generating new variables

Aug 28, 2018 at 9:40pm
Is there a way to declare/create a variable after a program is executed is with a name that is obtained from data obtained after the program is executed? For example, if I had:


string fruit = "apple";

can I refer to string fruit to name an int apple?
Aug 28, 2018 at 10:04pm
What do you actually want to achieve?


Does this question somehow relate to your earlier problem?
http://www.cplusplus.com/forum/general/237687/
Aug 29, 2018 at 3:05am
Is a factory model what you want? Do you want a scripting environment?

I think you need to be more clear and precise with your problem. In your previous topic, I am completely lost with what you are trying to accomplish, it doesn't seem like a something teacher would give homework for.
Last edited on Aug 29, 2018 at 4:01am
Aug 29, 2018 at 2:21pm
there are many ways. You can use a union of the types for a very simple approach. You can use a class template. You can use a class with a "what am i" member. You can use void *. And those are just a few ways to do it. You can just use a wad of bytes (array of unsigned char for example) and jam the data into it with pointer magic.

names are the weird part. You can't write the program to reference variables you have not created yet; it won't compile. But you can store the data and use it, and have a 'name' on it that you can search for, etc. so you can't do this:

myvarcreate(); //creates fruit variable
fruit = 10; // undeclared at compile time, no good.

what you end up with is this

generic = myvarcreate(); //creates fruit variable
if(generic.name == "fruit")
{
generic.value = 10;
}

or code to that effect.

Last edited on Aug 29, 2018 at 2:22pm
Aug 30, 2018 at 12:55pm
can I refer to string fruit to name an int apple?


no, you would have to maintain storage yourself.

1
2
3
4
5
6
7
std::map<std::string,int> myInts;
std::map<std::string, float> myFloats;

myInts["apple"] = 10;
myInts["basket_size"] = 24;

int aBasketFull = myInts["basket_size"] * myInts["apple"];
Topic archived. No new replies allowed.