开发者

C++ conversion from string to object identifier [duplicate]

开发者 https://www.devze.com 2022-12-31 10:42 出处:网络
This question already has answers here: converting a variable name to a string in C++ 开发者_开发知识库
This question already has answers here: converting a variable name to a string in C++ 开发者_开发知识库 (8 answers) Reference a variable by name in C++ by using Symbol Table (2 answers) Closed 5 years ago.

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)


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


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

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号