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

前端 未结 8 591
醉酒成梦
醉酒成梦 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条回答
  •  无人共我
    2021-02-07 03:57

    If you have C++11:

    auto res = some_complicated_expression_with_ugly_return_type;
    if (res == A
        || res == C
        || res == E
        || res == G) {
    }
    

    if not, you can still eliminate the type declaration by using a template function:

    template 
    bool matches(T t) {
        return t == A || t == C || t == E || t == G;
    }
    
    if (matches(some_complicated_expression_with_ugly_return_type)) {
    }
    

提交回复
热议问题