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

  • The Modern C++ Challenge
  • Marius Bancila
  • 125字
  • 2021-06-25 22:01:27

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, " "));
}
主站蜘蛛池模板: 游戏| 教育| 丰原市| 富顺县| 喀喇| 宣武区| 达拉特旗| 宁德市| 茶陵县| 阳东县| 盐山县| 大姚县| 安岳县| 华坪县| 长海县| 西和县| 玉树县| 岳池县| 中宁县| 新闻| 常德市| 永州市| 伊金霍洛旗| 彩票| 浦东新区| 姚安县| 腾冲县| 和顺县| 昔阳县| 南京市| 昌邑市| 长顺县| 外汇| 屯留县| 泰宁县| 南昌县| 若尔盖县| 双城市| 陆丰市| 汽车| 商都县|