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

前端 未结 8 603
醉酒成梦
醉酒成梦 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 04:02

    (Edit: Turns out my original trick with a dummy type didn't work, I was misled by a lucky accident in my tests. Let's try that again...)

    With a couple of helper templates you can write a general solution for this kind of situation:

    template  class Matcher {
    public:
        explicit Matcher(T1 t1): val(t1), flag(false) {}
        template  Matcher& operator()(T2 t2)
            { flag |= val == t2; return *this; }
        operator bool() const { return flag; }
    private:
        T1 val;
        bool flag;
    };
    template  Matcher match(T1 t1) { return Matcher(t1); }
    
    // example...
    string s = whatever;
    if (match(s)("foo")("bar")("zap")) { do_something(); }
    

    You can match against as many arguments as you want.

提交回复
热议问题