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

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, " "));
}
主站蜘蛛池模板: 建昌县| 台江县| 珲春市| 饶河县| 额尔古纳市| 翁源县| 涟水县| 沾益县| 保德县| 称多县| 望奎县| 本溪| 应城市| 建平县| 东阳市| 黔江区| 临桂县| 新平| 浠水县| 怀化市| 简阳市| 丹巴县| 崇仁县| 景泰县| 普格县| 孝昌县| 兴仁县| 南和县| 宁波市| 运城市| 恭城| 谢通门县| 惠东县| 钟祥市| 壶关县| 满城县| 元朗区| 萨嘎县| 苏尼特右旗| 同江市| 荥经县|