c++ - "Why switch statement cannot be applied on strings?"的答案是否仍然正确,即使使用 C++11/14?

标签 c++ string c++11 std stdstring

我遇到了这个问题: Why switch statement cannot be applied on strings? 并想知道答案是否:

The reason why has to do with the type system. C/C++ doesn't really support strings as a type. It does support the idea of a constant char array but it doesn't really fully understand the notion of a string.

仍然适用,即使在 C++11/14 中使用 std:string。是否有多个 else if(...) 的替代方案?

最佳答案

是的,它仍然成立。
如前所述here ,条件可以是:

any expression of integral or enumeration type, or of a class type contextually implicitly convertible to an integral or enumeration type, or a declaration of a single non-array variable of such type with a brace-or-equals initializer.

我遇到了 that question几天前,我猜你可以从那里找出 if/else 链的替代解决方案。
如果可能的话,这主要取决于您的实际问题,无论如何,基本思想是使用可调用对象的映射,从中使用您的对象(在本例中为字符串)作为键进行访问。当然,在使用之前必须以某种方式填充该 map 。

关于c++ - "Why switch statement cannot be applied on strings?"的答案是否仍然正确,即使使用 C++11/14?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35386918/

相关文章:

c++ - 如何在 C++ 中实现对函数的二分查找?

Java正则表达式检查时间格式

python - 使用 python 打印彩色字符串到控制台

c++ - 隐式声明的(对象级)成员函数如何根据 ISO C++11 标准工作?

c++ - 默认启动策略和 std::launch::deferred 之间的区别

c++ - 如何检查类型是否属于给定的模板类型

c++ - Visual Basic 和 C++

c++ - Python sprintf 和 memset 操作

c++ - 使用 40 个不同的 'identities' Vs 运行相同的程序。运行程序的 40 个实例。优点和缺点?

c++ - 这段代码有什么问题? (将 char* 转换为字符串)