Search code examples
c++debuggingvariadic-functionsvariadic

Push_back variadic function parameters into a vector?


I am trying to push_back the parameters of a variadic function as shown below, but the compiler says there is a type mismatch (due to the parameters being a general type while the vector is int). What should I do to make the parameters compatible?

vector<int> x;
template<typename... Rest>
void foo(Rest... rest) {
    x.push_back(rest...);
}

Solution

  • In C++14 and before:

    void foo(Rest... rest) {
        int a[] = {0, (x.push_back(rest), 0)...};
        static_cast<void>(a);  // unused
    }
    

    In C++17:

    void foo(Rest... rest) {
        (x.push_back(rest), ...);
    }