Search code examples
c++compareparameter-passinginfinite

How to create a method that compares an unknown number of strings in C++?


After some research I found that in C++ I can create a function with infinite variables in this way:

template<typename ... Args>
void func(Args... a) {
    /* CODE */
}

I want to make a method that compares an unknown number of strings and gives a bool: true if are equal and false if are not equal.

I did something like this but I don't know how to iterate the strings.

template<typename ... Strings>
bool cmp(string first, Strings... rest) {
    /* ITERATE AND COMPARE */

    return false;
}

So how I can iterate them?


Solution

  • The term infinite variables is not correct. C++ can handle variable numbers of function arguments but not infinitely many ones.

    If you can use C++17 a fold expression would be the easiest solution:

    template<typename ... Ts>
    bool cmp(const std::string& first, const std::string& second, const Ts&... rest) {
        return (cmp(second, rest) && ... && (second == first));
    }
    

    Again using C++17 you can also use a recursive approach using if constepxr:

    template<typename ... Ts>
    bool cmp(const std::string& first, const std::string& second, const Ts&... rest) {
        if constexpr (!sizeof...(Ts)) {  // Do we have only two arguments left?
            return first == second;
        } else {
            return first == second && cmp(second, rest...);
        }
    }
    

    For C++14 you can simply overload the two argument version and use again recursion:

    bool cmp(const std::string& first, const std::string& second) {
        return first == second;
    }
    
    template<typename ... Ts>
    bool cmp(const std::string& first, const std::string& second, const Ts&... rest) {
        return first == second && cmp(second, rest...);
    }