Reputation: 88238
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:
X["sigma"]
is not in Y
, i.e. the mapping is not necessarily one-to-oneY.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]
Upvotes: 2
Views: 642
Reputation: 1683
You want to set a field in an object of structure type based on the value of key in the map's elements (which is a string). So, no it cannot be done at compile time.
Upvotes: 0
Reputation: 180245
No. C++ has no concept of reflection. At compile time, there's no "foo::N"
string anymore. The compiler has converted all occurances of foo::N
in the source code to a 0 byte offset within Foo
objects. Also, you cannot enumerate class members at compile time.
Upvotes: 4