2

I have a std::map<string, double> whose members look something like:

X = [{"N", 200}, {"sigma", 1.0}, {"T", .2}]

Now, given the struct foo Y:

struct foo {
    int N;
    double T;
};

Can I programmatically map the key/value pairs X -> Y without writing a custom class for each X -> Y type mapping? Note that:

  1. X["sigma"] is not in Y, i.e. the mapping is not necessarily one-to-one
  2. The type of Y.N is an int while X["N"] is a double.

I suspect the answer is no, unless some trickery is done at compile time.

Edit: It may not be clear what I'm looking for. A pseudo-code version for this example would look something like:

if("N" in X) -> Y.N = X["N"];
if("T" in X) -> Y.T = X["T"];

Or programmatically:

for key in Y:
    if (key in X) -> Y.key = X[key]
4

2 回答 2

4

不,C++ 没有反射的概念。在编译时,"foo::N"不再有字符串。编译器已将foo::N源代码中的所有出现转换为对象内的 0 字节偏移量Foo。此外,您不能在编译时枚举类成员。

于 2012-06-07T15:32:36.047 回答
0

您想根据地图元素中的键值(这是一个字符串)在结构类型的对象中设置一个字段。所以,不,它不能在编译时完成。

于 2012-06-07T15:52:07.807 回答