lundi 28 décembre 2015

Defaulted parameter after parameter pack

This is an extension of the standard std::max function, so it can take a random amount of arguments.

template<typename T, typename U, typename Compare = std::greater<>> constexpr
const auto max(const T& first, const U& second, Compare comp = Compare())
{
    return comp(first, second) ? first : second;
}

template<typename T, typename U, typename... Pack, typename Compare = std::greater<>> constexpr
const auto max(const T& first, const U& second, const Pack&... rest, Compare comp = Compare())
{
    return comp(first, second) ? max(first, rest..., comp) : max(second, rest..., comp);
}

As I understand, the comp parameter will take the value of the last argument with which I call the function.

Am I wrong? What can I do about it?

std::cout << max(2, 3, 4, 5); //boom
std::cout << max(2, 3, 4, 5, std::greater<>()); //boom

Of course it works fine if I remove comp entirely.

Aucun commentaire:

Enregistrer un commentaire