Searchable Enum-like object with string and int conversion

后端 未结 2 1459
感动是毒
感动是毒 2020-12-29 05:36

Intro

The enum type in C++ is fairly basic; it basically just creates a bunch of compile-time values for labels (potentially with proper scoping with

2条回答
  •  清歌不尽
    2020-12-29 06:04

    Sometimes when you want to do something that isn't supported by the language, you should look external to the language to support it. In this case, code-generation seems like the best option.

    Start with a file with your enumeration. I'll pick XML completely arbitrarily, but really any reasonable format is fine:

    
        
        
        
    
    

    It's easy enough to add whatever optional fields you need in there (do you need a value? Should the enum be unscoped? Have a specified type?).

    Then you write a code generator in the language of your choice that turns that file into a C++ header (or header/source) file a la:

    enum class MyEnum {
        ALPHA,
        BETA,
        GAMMA,
    };
    
    std::string to_string(MyEnum e) {
        switch (e) {
        case MyEnum::ALPHA: return "ALPHA";
        case MyEnum::BETA: return "BETA";
        case MyEnum::GAMMA: return "GAMMA";
        }
    }
    
    MyEnum to_enum(const std::string& s) {
        static std::unordered_map m{
            {"ALPHA", MyEnum::ALPHA},
            ...
        };
    
        auto it = m.find(s);
        if (it != m.end()) {
            return it->second;
        }
        else {
            /* up to you */
        }
    }
    

    The advantage of the code generation approach is that it's easy to generate whatever arbitrary complex code you want for your enums. Basically just side-step all the problems you're currently having.

提交回复
热议问题