官术网_书友最值得收藏!

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),
std::ostream_iterator<int>(std::cout, " "));

std::list<int> l;
push_back(l, 1, 2, 3, 4);
std::copy(std::begin(l), std::end(l),
std::ostream_iterator<int>(std::cout, " "));
}
主站蜘蛛池模板: 额尔古纳市| 阿克| 澳门| 科技| 梁山县| 卓尼县| 水城县| 左云县| 天镇县| 潞城市| 苏尼特右旗| 宁蒗| 合肥市| 铜鼓县| 开封市| 宣城市| 汉寿县| 广丰县| 广丰县| 苏尼特左旗| 察隅县| 怀化市| 泰宁县| 岳西县| 淮北市| 禄劝| 万载县| 聂荣县| 永修县| 休宁县| 洪雅县| 宁德市| 正安县| 阜城县| 开封市| 叙永县| 库尔勒市| 海晏县| 绍兴市| 泰安市| 金沙县|