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

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);
}
主站蜘蛛池模板: 河津市| 肇庆市| 宁明县| 武城县| 封开县| 大冶市| 韶关市| 广元市| 独山县| 依兰县| 鞍山市| 乌拉特前旗| 灵武市| 梁平县| 巴青县| 昌邑市| 江西省| 莱西市| 阿克| 同仁县| 漳州市| 密山市| 定陶县| 定西市| 施甸县| 雅安市| 和平区| 婺源县| 黑河市| 五家渠市| 额济纳旗| 丹寨县| 拉孜县| 乌拉特前旗| 西乌珠穆沁旗| 宁武县| 西吉县| 永寿县| 乳山市| 连州市| 平和县|