C++ conversion from string to object identifier [d

2019-02-25 08:04发布

问题:

This question already has an answer here:

  • converting a variable name to a string in C++ 7 answers
  • Reference a variable by name in C++ by using Symbol Table 2 answers

I'm writing a program in C++ that reads in some data from an external file in order to set the values of static variables.

Is it possible to convert a string to an object identifier? (e.g. convert the string "CheckBox::Unchecked" into an identifier for the object CheckBox::unchecked)

回答1:

No. If you want to do this, you will have to parse the string manually and do the work yourself.



回答2:

No, it is not, unless you have a mapping method defined in your program.

You could create a hash and look this up, however.



回答3:

It's definitely possible. How you do it depends on what input you expect. For example, if you know you're about to read a checkbox string, then create an operator>>() for the checkbox class.

std::istream& operator>>(std::istream& in, CheckBox& cb)
{
    std::string input_str;
    in >> input_str;
    if( str == "CheckBox::unchecked" ) cb.set_value(false);
    else if( str == "CheckBox::checked" ) cb.set_value(true);
    else in.setstate(ios::badbit);
    return in;
}

// ...
CheckBox b;
if( !( cin >> b) )
    // ...

If you don't know what you're about to read then you're in the grammar and parsing domain. For that, you must define your grammar (when is the "checkbox" string allowed?). Once you have the grammar written down you write a lexer and a parser. There are tools for that.