3

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
  • 1
    @Ciro: This is the other direction. Commented Jan 1, 2017 at 23:31

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

1

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.

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.