Ansel Chang
Ansel Chang

Reputation: 203

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...);
}

Upvotes: 3

Views: 2417

Answers (3)

Olli
Olli

Reputation: 49

You should prefer this version as it's faster and works on C++11 too.

template<typename... Rest>
void foo(Rest... rest) {
    x.insert(x.end(), { static_cast<decltype(x)::value_type>(rest)...});
}

But if you for some reason need to use push_back() then at least call reserve() to make it faster.

template<typename... Rest>
void foo(Rest... rest) {
    x.reserve(sizeof...(Rest));
    (x.push_back(rest), ...);
}

Upvotes: 0

John Smith
John Smith

Reputation: 169

Start with a base case:

void push_all(vector<int>&) {}

Continue with 'gradual unpacking'

template<typename... Rest>
void push_all(vector<int>& vec, int val, Rest... rest)
{
    vec.push_back(val);
    push_all(vec, rest...);
}

Not as compact, but a little easier to grok.

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477030

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), ...);
}

Upvotes: 8

Related Questions