快速检查一系列枚举值的方法

rub*_*nvb 7 c++ enums

是否有一种快速/在线的synatx怪异方式,允许您检查枚举是否具有指定值的值?

例:

enum fruit_and_vegetables
{
    apples,
    pears,
    tomatoes,
    cucumbers
}

int main()
{
    fruit_and_vegetables something = apples;
    if( something = {apples, pears} ) // <-- this here
        cout << "something is fruit." << endl;
    else
        cout "something is a vegetable." << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Edw*_*nge 5

if (something < tomatoes)...


bit*_*ask 5

不是我知道,但你可以做的是2^i为枚举成员分配值.例如:

enum fruit_and_vegetables
{
    apples    = (1<<0),
    pears     = (1<<1),
    tomatoes  = (1<<2),
    cucumbers = (1<<3)
    // ...
}
Run Code Online (Sandbox Code Playgroud)

然后你可以检查

if (something & (apples | pears | tomatoes))
  std::cout << "is tasty" << std::endl;
Run Code Online (Sandbox Code Playgroud)

当然,这仅限于具有合理大小的枚举(我认为你最多可以有32个元素).

编辑

如果您的值超过32(64),则必须比此更有创意.通过多次检查,您仍可以相当快速地完成:

enum fruit_and_vegetables {
    apples    = 1, //!
    pears,
    tomatoes,
    cucumbers,
    // ...
    grapes
}
#define FRUIT_AND_VEGETABLES 120

if (   (1<<something)     & ((1<<apples) | (1<<pears) | (1<<tomatoes))
    || (1<<(something-32) & ((1<<(apples-32)) | (1<<(pears-32)) | (1<<(tomatoes-32))))
    || ...) {
  std::cout << "my keyboard is broken, but tastes good" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

但这不是一个很好的解决方案.如果你有大量的枚举,并且可以将它们分成几个类,那么我会选择Noah Roberts的答案.

  • 你在开玩笑吧!西红柿真棒! (2认同)
  • @bitmask:如果枚举包含70个成员怎么办?这种leftshift方法不起作用! (2认同)

Chr*_*man 4

啊,这可以很容易地完成......

template <typename T>
pair<T, fruit_and_vegetables> operator||(T t, fruit_and_vegetables v) {
    return make_pair(t, v);
}

template <typename T>
bool operator==(fruit_and vegetables lhs, pair<T, fruit_and_vegetables> rhs) {
    return lhs == rhs.second || lhs == rhs.first;
}
Run Code Online (Sandbox Code Playgroud)

然后可以像这样使用:

if (something == (apple || pear || orange)) eat_the_yummy_fruit(something);
else feed_to_rabbit(something)
Run Code Online (Sandbox Code Playgroud)

但如果你这样做就行不通(apple || (pear || orange))。这个问题可以很容易地解决,但我想保持代码简单。我相信这是迄今为止唯一可以实际扩展到大型枚举的答案......