gpt4 book ai didi

c++ - 如何在 C++ 中的 switch 中使用 bool 表达式

转载 作者:行者123 更新时间:2023-11-28 02:47:11 25 4
gpt4 key购买 nike

我需要将 if else 转换成 switch 语句,请帮忙:

if (XMLString::compareString(xmlch_Title, XMLString::transcode("abc")) == 0 ) {
out_Config.abc = XMLString::transcode(xmlch_Value);
} else if (XMLString::compareString(xmlch_Title, XMLString::transcode("def")) == 0 ) {
out_Config.def = XMLString::transcode(xmlch_Value);
} .......

最佳答案

Note: Using a boolean expression as the condition of a switch would, in your case, be of little use since you then could only have two possible outcomes of the switch-statement:

Going to "case true: ", or "case false: "


简介

如标准 ( n3797 ) 中所述,与开关一起使用的条件必须可隐式转换为整数或枚举类型。

6.4.2p2 The switch statement [stmt.switch]

The condition shall be of integral type, enumeration type, or class type. If of class type, the condition is contextually implicitly converted (Clause 4) to an integral or enumeration type**. Integral promotions are performed. Any statement within the switch statement can be labeled with one or more case labels as follows:

case constant-expression:

where the constant-expression shall be a converted constant expression (5.19) of the promoted type of the switch condition. No two of the case constans in the same switch shall have the same value after conversion to the promoted type of the switch condition.


这意味着下面的理论实现是错误的,因为 std::string 不能隐式转换为整数或枚举类型(1),而且它也不能用于常量表达式 (2)

std::string get_string ();

switch (get_string ()) {            //          (1)
case std::string ("stack"): ...; // <----.
case std::string ( "over"): ...; // <----|-- (2)
case std::string ( "flow"): ...; // <----'
}



我完全不走运吗?

不是真的,如果你要使用 hashing function为所涉及的字符串生成散列,理论上您可以使用开关;请注意所述散列的潜在冲突。

另请注意,对于 case-labelsconstant-expressions 中必须有可用的实现。

为了解决这类问题值得写这么复杂的代码吗?可能不是。

关于c++ - 如何在 C++ 中的 switch 中使用 bool 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24018164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com