I\'m implementing variadic min/max functions. A goal is to take advantage of the compile time known number of arguments and perform an unrolled evaluation (
4) Here is one possible way to implement a constexpr
version of this function:
#include
#include
template
constexpr typename std::common_type::type vmin(Arg1&& arg1, Arg2&& arg2)
{
return arg1 < arg2 ? std::forward(arg1) : std::forward(arg2);
}
template
constexpr typename std::common_type::type vmin(Arg&& arg, Args&&... args)
{
return vmin(std::forward(arg), vmin(std::forward(args)...));
}
int main()
{
std::cout << vmin(3, 2, 1, 2, 5) << std::endl;
std::cout << vmin(3., 1.2, 1.3, 2., 5.2) << std::endl;
}
See live example.
Edit: As @Yakk noted in comments the code std::forward
may cause problems in some situations. arg1 < arg2 ? std::forward
is more appropriate variant in this case.