String to enum in C++

后端 未结 10 1654
渐次进展
渐次进展 2020-11-28 07:15

Is there a way to associate a string from a text file with an enum value?

The problem is: I have a few enum values stored as string in a text file which I read on

10条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 07:54

    Using C++ reflection library from here: https://github.com/tapika/cppreflect

    You can - include library like this:

    #include "cppreflect/cppreflect.h"
    

    Basic usage:

    Declare enumeration:

    DECLARE_ENUM( enumName,
        // Prefix for all enums, "" if no prefix used.
        "myenum_",
    
        myenum_enumValue1,
        myenum_enumValue2,
        myenum_enumValue3 = 5,
    
        // comment
        myenum_enumValue4
    );
    

    Conversion logic:

    From enumeration to string:

    printf( EnumToString(myenum_enumValue3).c_str() );
    
    => "enumValue3"
    

    From string to enumeration:

    enumName value;
    
    if( !StringToEnum("enumValue4", value) )
        printf("Conversion failed...");
    
    => 
    
    value == myenum_enumValue4
    

    Main / core functionality resides in here:

    https://github.com/tapika/cppreflect/blob/master/cppreflect/enumreflect.h

提交回复
热议问题