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

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

    C++11:

    template
    bool equalsOneOf (T1&& value, T2&& candidate) {
       return std::forward(value) == std::forward(candidate);
    }
    
    template
    bool equalsOneOf (T1&& value, T2&& firstCandidate, T&&...otherCandidates) {
       return (std::forward(value) == std::forward(firstCandidate))
         || equalsOneOf (std::forward (value), std::forward(otherCandidates)...);
    }
    
    if (equalsOneOf (complexExpression, A, D, E)) { ... }
    

    C++03:

    template
    bool equalsOneOf (const T& value, const C& c) { return value == c; }
    
    template
    bool equalsOneOf (const T& value, const C1& c1, const C2& c2) {
        return (value == c2) || equalsOneOf (value, c1);
    }
    
    template
    bool equalsOneOf (const T& value, const C1& c1, const C2& c2, const C3& c3) {
        return (value == c3) || equalsOneOf (value, c1, c2);
    }
    
    template
    bool equalsOneOf (const T& value, const C1& c1, const C2& c2, const C3& c3, const C4& c4) {
        return (value == c4) || equalsOneOf (value, c1, c2, c3);
    }
    
    template
    bool equalsOneOf (const T& value, const C1& c1, const C2& c2, const C3& c3, const C4& c4, const C5& c5) {
        return (value == c5) || equalsOneOf (value, c1, c2, c3, c4);
    }
    
    // and so on, as many as you need
    

提交回复
热议问题