C++ comparing bunch of values with a given one

后端 未结 10 927
一向
一向 2021-01-21 06:02

I need to compare one given value with a retrieved values. I do this several times in the code. I am not satisfied with how it looks and I am seeking for a some sort of an util

10条回答
  •  情话喂你
    2021-01-21 06:49

    you can write a set of template functions which will help you through with this, for example:

    template 
    bool InSet(const T & item, const T & i1, const T & i2) {
      return item==i1 || item==i2;
    }
    
    template 
    bool InSet(const T & item, const T & i1, const T & i2, const T & i3) {
      return item==i1 || item==i2 || item==i3;
    }
    

    Note that you can make InSet to work like it took a variable number of arguments by creating multiple templates with different number of arguments.

    And then:

    int i;
    if (InSet(i, 3, 4, 5)) { ... }
    string s;
    if (InSet(s, "foobar", "zap", "garblex")) { ... }
    

    etc.

提交回复
热议问题