user2556165
user2556165

Reputation:

Error with variadiac template: "parameter pack must be expanded"

Here's a variadic template function that I've written:

template<class Container, class Value, class... Args>
Value& insert(Container& c, Args&&... args) {
    c.emplace_back(args);
    return c.back();
}

When I use insert like this I'm getting an error:

list<int> lst;
int& num = insert<list<int>, int, int>(lst, 4);

The error complains about this line in the body of insert:

c.emplace_back(args); // <= 'args' : parameter pack must be
                      //             expanded in this context

What does that mean and how can I fix it?

Upvotes: 26

Views: 24674

Answers (1)

Jarod42
Jarod42

Reputation: 218323

The error is due to the missing ellipsis (...) after args when passing all individual parameters (rather than the parameter pack) to emplace_back.

The fixed (and improved) version:

template<class Container, class... Args>
auto insert(Container& c, Args&&... args) -> decltype (c.back()) {
    c.emplace_back(std::forward<Args>(args)...);
    return c.back();
}

Upvotes: 42

Related Questions