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!

3
  • 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. Commented Feb 14, 2018 at 9: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. Commented Feb 14, 2018 at 9: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 <typename T> void setValue( T& variable_name, T value){ variable_name=value;} Commented Feb 14, 2018 at 9:56

1 Answer 1

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;
    // ...
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.