Accessing a class member variable by its name at runtime [duplicate]
In the vein of more impossible-but-is-it-really questions:
开发者_高级运维Is it possible to access the member variable of a class, where the variable's name is stored in a string?
class Test
{
public:
int test = 0;
}
string name = "test"; // let's assume we know test is an int.
Any chance of getting the value of test, using the string?
One bit of cheating not allowed:
enum vartype {
INT,
..
}
No forcing the class to register all its variables in a std::map<string, std::pair<vartype, void*> >
.
All other tricks welcome.
Thanks!
No.
To do this, you need to provide some mapping between member variables and the string names by which you intend to access them.
In the realm of really ugly kluges, you could build the program with debug information and have it use that to find the location of the variable in the same way a debugger would. But other than that, you're out of luck. C++ doesn't do reflection.
About why it's not available in C++ and an alternative: http://en.allexperts.com/q/C-1040/eval-function-javascript-C.htm
It's possible in MATLAB though... As a very simple example, if you have a matrix updation to do, which goes like:
M1=1;
M2=2;
M3=3;
And you would prefer that the variable names could be altered so that you could use a for loop, then it can also be done this way:
for i=1:3
eval(['M' num2str(i) '=' num2str(i)]);
end
I used to do this in Actionscript. Was really glad to find that it's available in Matlab too
精彩评论