Comparison tricks in C++

前端 未结 10 1852
礼貌的吻别
礼貌的吻别 2021-01-31 16:13

A class:

class foo{
public:
    int data;
};

Now I want to add a method to this class, to do some comparison, to see if its data is equal to on

10条回答
  •  离开以前
    2021-01-31 16:37

    It isn't pretty, but this should work:

    class foo {
        bool equals(int a) { return a == data; }
        bool equals(int a, int b) { return (a == data) || (b == data); }
        bool equals(int a, int b, int c) {...}     
        bool equals(int a, int b, int c, int d) {...} 
    private:
        int data; 
    }
    

    And so on. That'll give you the exact syntax you were after. But if you are after the completely variable number of arguments then either the vector, or std::initalizer list might be the way to go:

    See: http://en.cppreference.com/w/cpp/utility/initializer_list

    This example shows it in action:

    #include 
    #include 
    
    class foo {
    public:
            foo(int d) : data(d) {}
            bool equals_one_of(std::initializer_list options) {
                    for (auto o: options) {
                            if (o == data) return true;
                    }
                    return false;
            }
    private:
            int data;
    };
    
    int main() {
            foo f(10);
            assert(f.equals_one_of({1,3,5,7,8,10,14}));
            assert(!f.equals_one_of({3,6,14}));
            return 0;
    }
    

提交回复
热议问题