2

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);
0xFF
  • 4,140
  • 7
  • 41
  • 58
  • What type would that field have? Maybe you're better off using a `map`. – Ulrich Eckhardt Feb 12 '16 at 07:18
  • Who idea is that I don't know what the type of the field is, but what I can do is to provide templatized functions that serve as Compare, Less than, greater than etc for different field types... – 0xFF Feb 13 '16 at 05:44
  • 1
    I'd still say that `map` or `map>` is the way to go then. Using the reflection from Fusion only pays if you need certain things to be resolved at compile time. If you have to live with runtime evaluation of a few things anyway, using a map and general-purpose types (`any` or `variant`), possibly combined with the "Visitor Pattern" would be my approach. – Ulrich Eckhardt Feb 13 '16 at 08:18
  • Looks interesting indeed, I have no experience with `any` or `variant`. Do you have any examples leads on how to use them for this purpose? – 0xFF Feb 15 '16 at 04:31

0 Answers0