views:

68

answers:

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  A: 

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

DeadMG
+1  A: 

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

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

WhirlWind
A: 

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.

wilhelmtell