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

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, " "));
}
主站蜘蛛池模板: 古交市| 商都县| 沾化县| 澎湖县| 南召县| 汤阴县| 文登市| 团风县| 永定县| 泉州市| 陇南市| 海晏县| 任丘市| 桑日县| 常州市| 哈巴河县| 剑川县| 曲沃县| 白银市| 蓬安县| 多伦县| 麦盖提县| 公安县| 新乡市| 方山县| 广宗县| 鹿泉市| 昂仁县| 隆安县| 河池市| 平江县| 沙洋县| 宣城市| 探索| 黎川县| 神池县| 平定县| 泸定县| 莱芜市| 日土县| 阿拉善左旗|