jeudi 20 décembre 2018

map strings to class members

Say I have a class / struct like below:

struct A {
    uint32_t a;
    uint8_t  b;
    uint16_t c;
};

And I have a set of strings that associate to each member of A (could be of different integer types, but not non-integer types such as strings), e.g.

"field1" -> A::a
"field2" -> A::b
"field3" -> A::c

Assume that there is always a 1:1 mapping between the strings and members. Is there an elegant way to map each string to each member using something like std::unordered_map? I want to be able to read and write to each field using the strings as keys, e.g.

A a {1,2,3};
mymap["field1"] = 4; // a.a = 4
mymap["field2"] = 5; // a.b = 5
auto c = mymap["field3"]; // c = a.c = 3

I'm using C++11 and can't use boost.

Aucun commentaire:

Enregistrer un commentaire