0

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!

James McNellis
  • 338,529
  • 73
  • 897
  • 968
please delete me
  • 713
  • 2
  • 8
  • 17

3 Answers3

4

No.

To do this, you need to provide some mapping between member variables and the string names by which you intend to access them.

James McNellis
  • 338,529
  • 73
  • 897
  • 968
  • I'd also add: the variable + function names simply **don't exist** in the final executable – valdo Nov 22 '10 at 07:32
2

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.

Wyzard
  • 32,800
  • 3
  • 63
  • 86
0

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

Nav
  • 18,257
  • 26
  • 85
  • 127