You can't do this in C++ because it's a statically-typed language. One way to get this sort of behaviour is to provide accessing wrappers:
template <char c>
struct getter {
};
template <>
struct getter<'x'> {
static int get(const agnt &theAgnt) {
return theAgnt.x;
}
};
template <>
struct getter<'y'> {
static int get(const agnt &theAgnt) {
return theAgnt.y;
}
};
template <char c>
int get(const agnt &theAgnt) {
return getter<c>::get(theAgnt);
}
And call like:
agnt temp;
//... set members
std::cout << get<'x'>(temp) << std::endl;
However, the for
loop won't work the way you expect, because the template parameters need to be determined at compile time. Also, you can't just request any old thing, unless you define a get
function in the unspecialised getter
which returns some sort of NULL-indicator, like INT_MIN
.
However, this is all really a hack to get something vaguely similar to a dynamic language. But it's not really anything different from just referencing temp.x
. Instead, you should try to adhere to C++ conventions and enjoy the static typing!