switch/case statement in C++ with a QString type

后端 未结 14 2079
南笙
南笙 2020-12-16 10:19

I want to use switch-case in my program but the compiler gives me this error:

switch expression of type \'QString\' is illegal

How can I us

14条回答
  •  青春惊慌失措
    2020-12-16 10:30

    try this:

    // file qsswitch.h
    #ifndef QSSWITCH_H
    #define QSSWITCH_H
    
    #define QSSWITCH(__switch_value__, __switch_cases__) do{\
        const QString& ___switch_value___(__switch_value__);\
        {__switch_cases__}\
        }while(0);\
    
    #define QSCASE(__str__, __whattodo__)\
        if(___switch_value___ == __str__)\
        {\
        __whattodo__\
        break;\
        }\
    
    #define QSDEFAULT(__whattodo__)\
        {__whattodo__}\
    
    #endif // QSSWITCH_H
    

    how to use:

    #include "qsswitch.h"
    
    QString sW1 = "widget1";
    QString sW2 = "widget2";
    
    class WidgetDerived1 : public QWidget
    {...};
    
    class WidgetDerived2 : public QWidget
    {...};
    
    QWidget* defaultWidget(QWidget* parent)
    {
        return new QWidget(...);
    }
    
    QWidget* NewWidget(const QString &widgetName, QWidget *parent) const
    {
        QSSWITCH(widgetName,
                 QSCASE(sW1,
                 {
                     return new WidgetDerived1(parent);
                 })
                 QSCASE(sW2,
                 {
                     return new WidgetDerived2(parent);
                 })
                 QSDEFAULT(
                 {
                     return defaultWidget(parent);
                 })
                 )
    }
    

    there is some simple macro magic. after preprocessing this:

    QSSWITCH(widgetName,
             QSCASE(sW1,
             {
                 return new WidgetDerived1(parent);
             })
             QSCASE(sW2,
             {
                 return new WidgetDerived2(parent);
             })
             QSDEFAULT(
             {
                 return defaultWidget(parent);
             })
             )
    

    will work like this:

    // QSSWITCH
    do{
            const QString& ___switch_value___(widgetName);
            // QSCASE 1
            if(___switch_value___ == sW1)
            {
                return new WidgetDerived1(parent);
                break;
            }
    
            // QSCASE 2
            if(___switch_value___ == sW2)
            {
                return new WidgetDerived2(parent);
                break;
            }
    
            // QSDEFAULT
            return defaultWidget(parent);
    }while(0);
    

提交回复
热议问题