Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Q_ENUM and typedef


  • Qt Champions 2019

    Hi!
    I would like to use Q_ENUM with a typedef like bellow:

    class TestEnum
    {
        Q_GADGET
    public:
        TestEnum();
    
        typedef enum SomeEnum_
        {
            value1,
            value2,
            value3
        } SomeEnum;
        Q_ENUM(SomeEnum)
    
        void printEnum(SomeEnum value)
        {
            qDebug() << Q_FUNC_INFO;
    
            QMetaEnum metaEnum = QMetaEnum::fromType<SomeEnum>();
            qDebug() << metaEnum.isValid();
            qDebug() << "Key" << metaEnum.key(value);
        }
    };
    

    Without typedef it works as expected (the key name is printed). But with typedef it does not work and metaEnum.isValid() returns false. Is there a way to use Q_ENUM with enums declared using typedef?
    The reason why I would like to use typedef is that we give our own names to enums provided by the supplier using typedef.


  • Qt Champions 2017

    @jsulm
    Hi,
    If you're willing to live with the Q_ENUM macro referencing the non-aliased type, the QMetaEnum::fromType function will work as expected. I.e.:

    class TestEnum
    {
        typedef enum SomeEnum_
        {
        } SomeEnum;
        Q_ENUM(SomeEnum_) //< No alias for the macro
    
        void printEnum(SomeEnum value)
        {
            QMetaEnum metaEnum = QMetaEnum::fromType<SomeEnum>(); //< Works okay
        }
    };
    

    But I think you can't use a typedef-ed enum with the macro. If I'm not mistaken there's no way to deduce the corresponding meta-object this way, and consequently it doesn't work.


  • Qt Champions 2019

    The Q_ENUMS macro works with typedefs.


  • Qt Champions 2017

    @jsulm
    Yes, but the new macro is "smart" ... Here's a good article dealing with it, if you haven't stumbled on it, I suggest taking a quick look. If I had to guess what the problem is, I'd say it's the overloading rules that are confused, which is always a danger when working with templates. Most probably the trick with SFINAE they're using doesn't go well with aliased enums.
    I'm not that well versed in the internals, though, so I might simply be wrong.

    PS.
    You might get a more coherent answer on the mailing list.

    Kind regards.


Log in to reply