Convert C ++ from string to object id

I am writing a C ++ program that reads some data from an external file to set the values โ€‹โ€‹of static variables.

Is it possible to convert a string to an object identifier? (for example, convert the string "CheckBox :: Unchecked" to the identifier of the CheckBox :: unchecked object)

+3
source share
3 answers

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

+2
source

No, this is not the case if you do not have a matching method in your program.

However, you can create a hash and see it.

+1
source

It is definitely possible. How you do this depends on what contribution you expect. For example, if you know you are going to read a flag line, then create a operator>>()flag for the 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 do not know what you are going to read, then you are in the field of grammar and parsing. To do this, you must define your grammar (when is the "checkbox" line allowed?). Once you have written the grammar, you write the lexer and parser. There are tools for this.

+1
source

Source: https://habr.com/ru/post/1745595/


All Articles