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

  • 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, " "));
}
主站蜘蛛池模板: 苍梧县| 银川市| 铁力市| 郓城县| 碌曲县| 四川省| 景泰县| 行唐县| 安福县| 封丘县| 句容市| 龙井市| 方山县| 肥城市| 灵寿县| 新余市| 乌鲁木齐市| 潼关县| 电白县| 根河市| 清流县| 卓尼县| 淳安县| 铜鼓县| 郴州市| 襄垣县| 德安县| 洪湖市| 洮南市| 吉隆县| 蛟河市| 湘潭县| 庆阳市| 赤城县| 高邑县| 临洮县| 沾益县| 左贡县| 霍城县| 扶风县| 枣阳市|