jeudi 11 février 2016

C++ Access struct member by string reference [reflection]

Say I have a struct like the following:

struct employee
{
    std::string name;
    int age;
};

With boost fusion I can decorate the struct:

BOOST_FUSION_ADAPT_ASSOC_STRUCT(
    demo::employee,
    (std::string, name)
    (int, age)
)

And access its members like this:

employee e;
boost::fusion::at_c<0, employee>(e)

Is there any way, at runtime, to get from a string "name" to the struct field name?

The scenario of the code will be like this:

employee e; // or some other struct determined at runtime!
string attribute;
cin >> attribute;

// ApplyVisitor would inspect the correct field from the struct and act on it.
cout << ApplyVisitor(e, attribute);





Aucun commentaire:

Enregistrer un commentaire