Answer the question
In order to leave comments, you need to log in
How to refer to a structure field by its string representation in C++ (Arduino)?
Comrades! Please tell me how to solve the following problem in the C++ (Arduino) ideology:
there is a structure
struct DataStruct
{
int Data1;
intData2;
};
struct DataStruct Content;
You need to refer to Content.Data1 or Content.Data2 depending on the external condition. There are a lot of fields in the original structure, so the if constructs do not work.
How to access the desired field using the template Content.Data[string type. field number]?
Answer the question
In order to leave comments, you need to log in
I think it’s no longer relevant, but a person needs to give the correct answer even if it’s not quite correct, who said that it’s impossible!?:
struct DataStruct {
#define Data(n) Data##n;
int Data1;
int Data2;
};
struct DataStruct Content;
Content.Data(1);
Content.Data(2); // и т.д.
No way. But you can replace the structure with std::map , for example.
You can create a std::map, initialize it with the names and addresses of the structure fields, and walk through this map, like this:
struct DataStruct {
int Data1;
int Data2;
};
struct DataStruct Content;
...
std::map<std::string, int DataStruct::*> data_struct_field;
...
data_struct_field["Data1"] = &DataStruct::Data1;
data_struct_field["Data2"] = &DataStruct::Data2;
...
Content.*data_struct_field["Data1"] = 1;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question