假设我有一堆众所周知的价值观,就像这样(但是const char *
这只是一个例子,可能更复杂):
const char *A = "A", *B = "B", *C = "C", *D = "D", *E = "E", *F = "F", *G = "G";
现在假设如果某个表达式的结果位于这些表达式的子集中,我想以特定的方式表现:
if (some_complicated_expression_with_ugly_return_type == A ||
some_complicated_expression_with_ugly_return_type == C ||
some_complicated_expression_with_ugly_return_type == E ||
some_complicated_expression_with_ugly_return_type == G)
{
...
}
我发现自己经常输入此类内容,因此我想要一个简写形式。
如果语言是 Python,我可以轻松地说:
if some_complicated_expression_with_ugly_return_type in [A, C, E, G]:
...
有没有一种众所周知的、可移植的方式让我在 C++03 中类似地表达这一点?
请注意,返回类型本身很丑陋(几乎与返回类型一样丑陋)lambda 表达式 http://www.boost.org/doc/libs/1_51_0/doc/html/typeof.html#typeof.moti),所以我当然不想将它存储在局部变量中。
但返回类型确实如此not必须与常量匹配——例如,如果返回类型是std::string
, 它会not可以隐式转换为const char *
, but operator ==
非常适合比较。
到目前为止,我最好的解决方案是这样说:
const char *items[] = { A, C, E, G };
if (std::find(items, items + sizeof(items) / sizeof(*items),
some_complicated_expression_with_ugly_return_type)
!= items + sizeof(items) / sizeof(*items))
{
...
}
但它实在是太丑了。有没有更好的方法,也适用于非 POD?