- 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, " "));
}
推薦閱讀
- Learning Single:page Web Application Development
- 信息可視化的藝術:信息可視化在英國
- Java應用開發與實踐
- Vue.js入門與商城開發實戰
- Learning RabbitMQ
- PHP+MySQL網站開發技術項目式教程(第2版)
- Access 2010數據庫基礎與應用項目式教程(第3版)
- 人人都是網站分析師:從分析師的視角理解網站和解讀數據
- Creating Stunning Dashboards with QlikView
- 持續輕量級Java EE開發:編寫可測試的代碼
- 區塊鏈技術進階與實戰(第2版)
- Mudbox 2013 Cookbook
- Python面試通關寶典
- 分布式數據庫HBase案例教程
- Kohana 3.0 Beginner's Guide