编译下面的代码会得到错误消息:type illegal。

int main()
{
    // Compilation error - switch expression of type illegal
    switch(std::string("raj"))
    {
    case"sda":
    }
}

你不能在switch或case中使用字符串。为什么?是否有任何解决方案可以很好地支持类似于打开字符串的逻辑?


当前回答

在许多情况下,您可以通过从字符串中提取第一个字符并打开它来进行额外的工作。如果您的case以相同的值开始,可能最终必须在charat(1)上进行嵌套切换。任何阅读您的代码的人都会喜欢一个提示,因为大多数人会只使用if-else-if

其他回答

这是我前段时间提出的一个解决方案,它完全遵守所请求的语法。

#include <uberswitch/uberswitch.hpp>

int main()
{
    uswitch (std::string("raj"))
    {
        ucase ("sda"): /* ... */ break;  //notice the parenthesis around the value.
    }
}

代码如下:https://github.com/falemagn/uberswitch

在c++中,你只能在int和char上使用switch语句

开关问题的更实用的解决方案:

class APIHandlerImpl
{

// define map of "cases"
std::map<string, std::function<void(server*, websocketpp::connection_hdl, string)>> in_events;

public:
    APIHandlerImpl()
    {
        // bind handler method in constructor
        in_events["/hello"] = std::bind(&APIHandlerImpl::handleHello, this, _1, _2, _3);
        in_events["/bye"] = std::bind(&APIHandlerImpl::handleBye, this, _1, _2, _3);
    }

    void onEvent(string event = "/hello", string data = "{}")
    {
        // execute event based on incomming event
        in_events[event](s, hdl, data);
    }

    void APIHandlerImpl::handleHello(server* s, websocketpp::connection_hdl hdl, string data)
    {
        // ...
    }

    void APIHandlerImpl::handleBye(server* s, websocketpp::connection_hdl hdl, string data)
    {
        // ...
    }
}

使用尽可能简单的容器添加一个变体(不需要一个有序的映射)…我不会使用枚举——只是把容器定义放在切换之前,这样就很容易看出哪个数字代表哪个情况。

这将在unordered_map中进行哈希查找,并使用相关的int来驱动switch语句。应该很快。注意,这里使用的是at而不是[],因为我已经将该容器设置为const。使用[]可能是危险的——如果字符串不在映射中,您将创建一个新的映射,并可能以未定义的结果或不断增长的映射结束。

注意,如果字符串不在映射中,at()函数将抛出异常。因此,您可能希望首先使用count()进行测试。

const static std::unordered_map<std::string,int> string_to_case{
   {"raj",1},
   {"ben",2}
};
switch(string_to_case.at("raj")) {
  case 1: // this is the "raj" case
       break;
  case 2: // this is the "ben" case
       break;


}

测试未定义字符串的版本如下:

const static std::unordered_map<std::string,int> string_to_case{
   {"raj",1},
   {"ben",2}
};
// in C++20, you can replace .count with .contains
switch(string_to_case.count("raj") ? string_to_case.at("raj") : 0) {
  case 1: // this is the "raj" case
       break;
  case 2: // this is the "ben" case
       break;
  case 0: //this is for the undefined case

}

如前所述,编译器喜欢构建查找表,尽可能地将switch语句优化到接近O(1)的时间。再加上c++语言没有字符串类型——std::string是标准库的一部分,而标准库本身不是语言的一部分。

我将提供一个你可能想要考虑的替代方案,我过去用过它,效果很好。不是切换字符串本身,而是切换使用字符串作为输入的哈希函数的结果。如果你使用一组预先确定的字符串,你的代码几乎和切换字符串一样清晰:

enum string_code {
    eFred,
    eBarney,
    eWilma,
    eBetty,
    ...
};

string_code hashit (std::string const& inString) {
    if (inString == "Fred") return eFred;
    if (inString == "Barney") return eBarney;
    ...
}

void foo() {
    switch (hashit(stringValue)) {
    case eFred:
        ...
    case eBarney:
        ...
    }
}

这里有一堆明显的优化,基本上遵循了C编译器对switch语句的处理……真有趣。