尽管如此,事实上,我们有std::max,我想尝试是否可以制作一个Max采用可变参数并递归调用Max 以查找最大元素的版本。
我在堆栈溢出中看到了类似的帖子,但这些帖子已经很旧了,而且大多数都std::max在内部使用。由于我有一个特定的错误并使用较新的编译器,因此这篇文章不容易重复。
以下是我写的代码:
#include <iostream>
#include <string>
#include <format>
using namespace std::string_literals;
template <typename T>
constexpr T Max(T&& value)
{
return value;
}
template <typename T, typename... Ts>
constexpr T Max(T&& value, Ts&&... args)
{
const T maxRest = Max(args...);
return (value > maxRest) ? value : maxRest;
}
int main()
{
std::cout << std::format("Maximum integer: {}\n", Max(1));
std::cout << std::format("Maximum integer: {}\n", Max(5, 2, 10, 6, 8));
std::cout << std::format("Maximum integer: …Run Code Online (Sandbox Code Playgroud)