Why the switch statement cannot be applied on strings?

前端 未结 20 2568
离开以前
离开以前 2020-11-22 03:58

Compiling the following code and got the error of type illegal.

int main()
{
    // Compilation error - switch expression of type illegal
    sw         


        
20条回答
  •  情歌与酒
    2020-11-22 04:41

    C++ 11 update of apparently not @MarmouCorp above but http://www.codeguru.com/cpp/cpp/cpp_mfc/article.php/c4067/Switch-on-Strings-in-C.htm

    Uses two maps to convert between the strings and the class enum (better than plain enum because its values are scoped inside it, and reverse lookup for nice error messages).

    The use of static in the codeguru code is possible with compiler support for initializer lists which means VS 2013 plus. gcc 4.8.1 was ok with it, not sure how much farther back it would be compatible.

    /// 
    /// Enum for String values we want to switch on
    /// 
    enum class TestType
    {
        SetType,
        GetType
    };
    
    /// 
    /// Map from strings to enum values
    /// 
    std::map MnCTest::s_mapStringToTestType =
    {
        { "setType", TestType::SetType },
        { "getType", TestType::GetType }
    };
    
    /// 
    /// Map from enum values to strings
    /// 
    std::map MnCTest::s_mapTestTypeToString
    {
        {TestType::SetType, "setType"}, 
        {TestType::GetType, "getType"}, 
    };
    

    ...

    std::string someString = "setType";
    TestType testType = s_mapStringToTestType[someString];
    switch (testType)
    {
        case TestType::SetType:
            break;
    
        case TestType::GetType:
            break;
    
        default:
            LogError("Unknown TestType ", s_mapTestTypeToString[testType]);
    }
    

提交回复
热议问题