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

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

    @DomTomCat's answer already touched on this, but since the question is specifically asking about Qt, there is a better way.

    Qt already has a hashing function for QStrings, but unfortunately Qt4's qHash is not qualified as a constexpr. Luckily Qt is open source, so we can copy the qHash functionality for QStrings into our own constexpr hashing function and use that!

    Qt4's qHash source

    I've modified it to only need one parameter (string literals are always null-terminated):

    uint constexpr qConstHash(const char *string)
    {
        uint h = 0;
    
        while (*string != 0)
        {
            h = (h << 4) + *string++;
            h ^= (h & 0xf0000000) >> 23;
            h &= 0x0fffffff;
        }
        return h;
    }
    

    Once you've defined this, you can use it in switch statements like so:

    QString string;
    // Populate the QString somehow.
    
    switch (qHash(string))
    {
        case qConstHash("a"):
            // Do something.
            break;
        case qConstHash("b"):
            // Do something else.
            break;
    }
    

    Since this method uses the same code Qt uses to calculate hashes, it will have the same hash collision resistance as QHash, which is generally very good. The downside is that this requires a fairly recent compiler--since it has non-return statements in the constexpr hashing function, it requires C++14.

提交回复
热议问题