Better way to say x == Foo::A || x == Foo::B || x == Foo::C || …?

前端 未结 8 692
醉酒成梦
醉酒成梦 2021-02-07 03:23

Let\'s say I have a bunch of well-known values, like this (but const char * is just an example, it could be more complicated):

const char *A = \"A\"         


        
8条回答
  •  萌比男神i
    2021-02-07 04:02

    You could use a switch:

    switch (some_complicated_expression_with_ugly_return_type) {
      case A: case C: case E: case G:
        // do something
      default:
        // no-op
    }
    

    This only works with integer and enum types, note.

    For more complex types, you can use C++11's auto, or for C++03, boost's BOOST_AUTO:

    auto tmp = some_complicated_expression_with_ugly_return_type;
    // or
    BOOST_AUTO(tmp, some_complicated_expression_with_ugly_return_type);
    
    if (tmp == A || tmp == C || tmp == E || tmp == G) {
      // ...
    }
    

提交回复
热议问题