C ++通过字符串引用访问struct成员[反射]

时间:2016-02-12 07:06:13

标签: c++ reflection boost-fusion

假设我有如下结构:

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

使用boost融合我可以装饰结构:

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

并像这样访问其成员:

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

在运行时,有没有办法从字符串"name"获取到struct字段 name

代码的场景将是这样的:

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);

0 个答案:

没有答案