0

If the title is not so suggestive I hope the explanation might help you understand my problem.

I have a function which sets some variables value. But the variables name I would like to provide it as a string, this way:

void setValue( const std:: string& variable_name, int value){ variable_name=value;}

then when I call this function like this:

setValue("variable", 10);

I will expect to execute set variable=10;

Any idea if this approach is possible or other ways I could have this behaviour? Thanks!

  • 1
    In C++ the variables have no names at run-time. You could use `std::map` if you want something that have names or use a library that provides reflection. It's also possible to make a mapping from names to variables but no generic way to do it. – Mihayl Feb 14 '18 at 09:47
  • Is it ever possible to achieve such effect using macroses and other features of metaprogramming? P.S. I don;t ask aobut is it efficient, or can be used in some specific task. Only possibility. – Nikita Smirnov Feb 14 '18 at 09:50
  • as mentioned by @A.A at runtime variable name is not available. But, there is a way to do it at compile time using template. `template void setValue( T& variable_name, T value){ variable_name=value;}` – army007 Feb 14 '18 at 09:56

1 Answers1

0

It is not possible to magically retrieve a variable from a run-time string. You need to provide a mapping in advance, which is probably not what you want. E.g.

int& getFromName(const std::string& s)
{
    if(s == "variable") return variable;
    if(s == "foo")      return foo;
    // ...
}
Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416