- The Modern C++ Challenge
- Marius Bancila
- 223字
- 2021-06-25 22:01:27
18. Minimum function with any number of arguments
It is possible to write function templates that can take a variable number of arguments using variadic function templates. For this, we need to implement compile-time recursion (which is actually just calls through a set of overloaded functions). The following snippet shows how the requested function could be implemented:
template <typename T>
T minimum(T const a, T const b) { return a < b ? a : b; }
template <typename T1, typename... T>
T1 minimum(T1 a, T... args)
{
return minimum(a, minimum(args...));
}
int main()
{
auto x = minimum(5, 4, 2, 3);
}
In order to be able to use a user-provided binary comparison function, we need to write another function template. The comparison function must be the first argument because it cannot follow the function parameter pack. On the other hand, this cannot be an overload of the previous minimum function, but a function with a different name. The reason is that the compiler would not be able to differentiate between the template parameter lists <typename T1, typename... T> and <class Compare, typename T1, typename... T>. The changes are minimal and should be easy to follow in this snippet:
template <class Compare, typename T>
T minimumc(Compare comp, T const a, T const b)
{ return comp(a, b) ? a : b; }
template <class Compare, typename T1, typename... T>
T1 minimumc(Compare comp, T1 a, T... args)
{
return minimumc(comp, a, minimumc(comp, args...));
}
int main()
{
auto y = minimumc(std::less<>(), 3, 2, 1, 0);
}
- Spring Cloud Alibaba核心技術與實戰案例
- Debian 7:System Administration Best Practices
- AWS Serverless架構:使用AWS從傳統部署方式向Serverless架構遷移
- Visual Basic程序設計(第3版):學習指導與練習
- Access 2010數據庫基礎與應用項目式教程(第3版)
- Java程序設計:原理與范例
- Hands-On Reinforcement Learning with Python
- 零基礎入門學習Python(第2版)
- Learning jQuery(Fourth Edition)
- 開源項目成功之道
- GitHub入門與實踐
- 后臺開發:核心技術與應用實踐
- Julia High Performance(Second Edition)
- 深度學習入門:基于Python的理論與實現
- UML基礎與Rose建模實用教程(第三版)