It's not possible to switch directly on strings in C++. However it's possible in Qt using QMetaEnum
as shown here: Q_ENUM
and how to switch on a string. You don't even need C++14 like in Anthony Hilyard's answer, and the matching cases are not the hashes of the strings so there's zero chance of hash collision
Basically QMetaEnum
can convert from string to enum value and vice versa so we'll use that to jump to the correct branch. One small limitation is that strings are enum values so the string must be a valid C++ identifier. But that's easy to workaround, just replace the special characters with a specific rule if necessary
To do that, first declare an enum with the strings to be used in switch cases as enumerator name in your class declaration. Then add the enum to the metadata with Q_ENUMS
in order for the program to search later.
#include <QMetaEnum>
class TestCase : public QObject
{
Q_OBJECT
Q_ENUMS(Cases) // metadata declaration
QMetaObject MetaObject;
QMetaEnum MetaEnum; // enum metadata
TestCase() :
// get information about the enum named "Cases"
MetaObject(this->staticMetaObject),
MetaEnum(MetaObject.enumerator(MetaObject.indexOfEnumerator("Cases"))
{}
public:
explicit Test(QObject *parent = 0);
enum Cases
{
THE, AT, IN, THIS // ... ==> strings to search, case sensitive
};
public slots:
void SwitchString(const QString &word);
};
Then just implement the needed switch inside SwitchString
after converting the string to the corresponding value with QMetaEnum::keyToValue
.
The comparison is case sensitive so if you want a case insensitive search, convert the input string to upper/lower case first. You can also do other transformations necessary to the string. For example in case you need to switch strings with blank spaces or forbidden characters in C++ identifiers, you may convert/remove/replace those characters to make the string a valid identifier.
void TestCase::SwitchString(const QString &word)
{
switch (MetaEnum.keyToValue(word.toUpper().toLatin1()))
// or simply switch (MetaEnum.keyToValue(word)) if no string modification is needed
{
case THE: /* do something */ break;
case AT: /* do something */ break;
case IN: /* do something */ break;
case THIS: /* do something */ break;
default: /* do something */ break;
}
}
Then just use the class for switching the strings. For example:
TestCase test;
test.SwitchString("At");
test.SwitchString("the");
test.SwitchString("aBCdxx");