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

后端 未结 14 1893
南笙
南笙 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:47

    If you can use a modern C++ compiler then you could compute a compile time hash value for your strings. In this answer there's an example of a rather simple constexpr hashing function.

    So a solution can look like this:

    // function from https://stackoverflow.com/a/2112111/1150303
    // (or use some other constexpr hash functions from this thread)
    unsigned constexpr const_hash(char const *input) {
        return *input ?
        static_cast<unsigned int>(*input) + 33 * const_hash(input + 1) :
        5381;
    }
    
    QString switchStr = "...";
    switch(const_hash(switchStr.toStdString().c_str()))
    {
    case const_hash("Test"):
        qDebug() << "Test triggered";
        break;
    case const_hash("asdf"):
        qDebug() << "asdf triggered";
        break;
    default:
        qDebug() << "nothing found";
        break;
    }
    

    It is still not a perfect solution. There can be hash collisions (hence test your program whenever you add/change case) and you have to be careful in the conversion from QString to char* if you want to use exotic or utf characters, for instance.

    For c++ 11 add CONFIG += c++11 to your project, for Qt5. Qt4: QMAKE_CXXFLAGS += -std=c++11

    0 讨论(0)
  • 2020-12-16 10:50
    case "the":
        //^^^ case label must lead to a constant expression
    

    I am not aware of qt, but you can give this a try. You can avoid switch and directly use == for comparison, if QString is no different than a normal std::string.

    if( word == "the" )
    {
       // ..
    }
    else if( word == "at" )
    {
       // ..
    }
    // ....
    
    0 讨论(0)
提交回复
热议问题