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

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);
}
主站蜘蛛池模板: 抚顺市| 垣曲县| 汕尾市| 文安县| 丘北县| 巴塘县| 兰溪市| 普格县| 页游| 乐至县| 民权县| 达日县| 南雄市| 浦城县| 青铜峡市| 肇东市| 遂宁市| 镇原县| 台州市| 崇义县| 拉萨市| 威宁| 杨浦区| 东港市| 托克托县| 林西县| 肃南| 高雄市| 张家川| 河北省| 静宁县| 石景山区| 交口县| 龙游县| 永寿县| 龙里县| 桂平市| 永泰县| 贡山| 修水县| 鹿泉市|