Creating an enum like structure for data types other than integral?



  • When creating enums we can get do something like this:

    enum Vals{
        Val1,
        Val2,
        Val3
    };
    

    Then access them Vals::Val2.
    I wanted something similar, but for strings. The closest I could get was this:

    struct Token{
        QString Invalid = " ";
        QString P1 = "X";
        QString P2 = "O";
    } tokens;
    

    Then accessing them like this: tokens.P1

    Are there other, better ways to make enum like structures for data types other than integrals?
    I could also use a map, hash, etc of course. I just like the Enum::Value syntax.


  • Qt Champions 2018

    @fcarney said in Creating an enum like structure for data types other than integral?:

    Are there other, better ways to make enum like structures for data types other than integrals?

    Not really, but you can "improve" your struct based solution by making the members static: then you don't have to create an instance of the struct and you can do:

    Token::Invalid
    

    Also, since enum values cannot be changed you should make the struct elements const:

    struct Token{
        static const QString Invalid;
        static const QString P1;
        static const QString P2;
    }
    
    const QString Token::Invalid = " ";
    const QString Token::P1 = "X";
    const QString Token::P2 = "O";
    

Log in to reply