C ++ Structs: get attribute by name

I strive for a more professional solution to the problem. I am working on a C ++ SOAP2 solution. I have a Strcut defintion of about 25 items

struct X { field 1; field 2; .. }; 

and I tring to fill it with some map values

 Map<String,String> A 

and it seems very disappointing to do such a thing n times

 X->xx = A["aaa"] 

every time I want to populate my SOAP message structure.

Question: Is it possible to call a struct element by name? * example: to handle abe as follows:

 X->get_instance_of("xx").set(A["aaa"]); 

and put it in a loop. *

Thanks,

+6
source share
5 answers

C ++ lacks the built-in reflection capabilities of more dynamic languages, so you cannot do what you would like to use in your language capabilities.

However, if all members are of the same type, you can do this with a map of member pointers and a little preparation:

  // typedef for the pointer-to-member typedef int X::*ptr_attr; // Declare the map of pointers to members map<string,ptr_attr> mattr; // Add pointers to individual members one by one: mattr["xx"] = &X::xx; mattr["yy"] = &X::yy; // Now that you have an instance of x... X x; // you can access its members by pointers using the syntax below: x.*mattr["xx"] = A["aa"]; 
+8
source

The short answer is no. This is C ++, a statically compiled language where the names of structure members are converted by the compiler to memory offsets. It is not dynamic, like PHP or Python, where the runtime is associated with all variable references.

+2
source

Not. C ++ is not reflected. Java though. Unsurprisingly, SOA-related material is more likely to come across languages โ€‹โ€‹like Java than to languages โ€‹โ€‹like C.

+1
source

It is impossible to do this; the information you need is no longer present at runtime. You could do something with map and some pointers, but to be honest, you probably should just wrap it in a function that takes a map and puts the values โ€‹โ€‹in the appropriate fields.

+1
source

You can create a wrapper object for your structure using access / get accessors, which allows you to iterate over string values โ€‹โ€‹to populate / read the underlying structure, which is static.

0
source

Source: https://habr.com/ru/post/909464/


All Articles