Dynamically assigning value to structure variable

2019-06-14 03:00发布

I am trying to dynamically assign values from a file to variables in a structure, but can't figure out how to do it. I have a structure:

struct abc {
 int age = 0;
 string name = "whatever";
} *ABC;

I also have a function that loops through a file that can read these values so I would end up with a line that contains the variable name and its value that would need to be updated. So, for example, I might end up with two variables like:

KEY="age"
VAL="21"

after it processes the first line of the following file:

age|21
name|bill

How would I assign the VAL value to the ABC struct variable KEY?

Thanks!

UPDATE:

So I'm looking to do something like:

ABC.KEY = VAL

meaning

ABC.age = 21

1条回答
趁早两清
2楼-- · 2019-06-14 03:38

What you're looking for is known as reflection, and C++ does not offer this capability.

If you want to match keys to members of the struct, you will have to build a structure and functions to do so yourself.

For example, you may consider this:

std::unordered_map<std::string, std::function<void(std::string, abc&)>> mapping;
mapping["age"] = [](std::string str, abc& a) { a.age = std::stoi(str); };
mapping["name"] = [](std::string str, abc& a) { a.name = str; }

Now you can use the map like

abc output;
auto key = ...;
auto value = ...;
if (mapping.find(key) == mapping.end())
    throw ...;
mapping[key](value, output);
查看更多
登录 后发表回答