19. Adding a range of values to a container

Writing functions with any number of arguments is possible using variadic function templates. The function should have the container as the first parameter, followed by a variable number of arguments representing the values to be added at the back of the container. However, writing such a function template can be significantly simplified using fold expressions. Such an implementation is shown here:

template<typename C, typename... Args>void push_back(C& c, Args&&... args){   (c.push_back(args), ...);}

Examples of using this function template, with various container types, can be seen in the following listing:

int main(){   std::vector<int> v;   push_back(v, 1, 2, 3, 4); std::copy(std::begin(v), std::end(v), ...

Get The Modern C++ Challenge now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.