Is there a simple way to convert C++ enum to string?

后端 未结 30 2280
我在风中等你
我在风中等你 2020-11-22 10:37

Suppose we have some named enums:

enum MyEnum {
      FOO,
      BAR = 0x50
};

What I googled for is a script (any language) that scans all

30条回答
  •  遇见更好的自我
    2020-11-22 11:12

    QT is able to pull that of (thanks to the meta object compiler):

    QNetworkReply::NetworkError error;
    
    error = fetchStuff();
    
    if (error != QNetworkReply::NoError) {
    
        QString errorValue;
    
        QMetaObject meta = QNetworkReply::staticMetaObject;
    
        for (int i=0; i < meta.enumeratorCount(); ++i) {
    
            QMetaEnum m = meta.enumerator(i);
    
            if (m.name() == QLatin1String("NetworkError")) {
    
                errorValue = QLatin1String(m.valueToKey(error));
    
                break;
    
            }
    
        }
    
        QMessageBox box(QMessageBox::Information, "Failed to fetch",
    
                    "Fetching stuff failed with error '%1`").arg(errorValue),
    
                    QMessageBox::Ok);
    
        box.exec();
    
        return 1;
    
    }
    

    In Qt every class that has the Q_OBJECT macro will automatically have a static member "staticMetaObject" of the type QMetaObject. You can then find all sorts of cool things like the properties, signals, slots and indeed enums.

    Source

提交回复
热议问题