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

前端 未结 8 604
醉酒成梦
醉酒成梦 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:45

    You could factor your current best solution into a template:

    template
    inline bool is_in(const A &a, B (&bs)[n]) {
      return std::find(bs, bs + n, a) != bs + n;
    }
    

    which you can use like

    X items[] = { A, C, E, G };
    if (is_in(some_complicated_expression_with_ugly_return_type, items))
      …
    

提交回复
热议问题