Home > Mobile >  Why can't I assign lambdas to function parameters as a default value?
Why can't I assign lambdas to function parameters as a default value?

Time:11-16

Take the following function:

template<typename T>
decltype(auto) find_median(T begin,
                           T end,
                           bool sorted = false,
                           auto comparison = [](auto a, auto b){return a < b;}){
    assert(begin != nullptr);
    assert(end != nullptr);
    return sorted ? find_median_sorted(begin, end) : find_median_unsorted(begin, end, comparison);
}

Note that I set the comparison param to a default value [](auto a, auto b){return a < b;}. So if I call this function like the following: find_median(std::addressof(arr), std::addressof(arr[9])) where arr is an std::array, this should work. But it doesn't work, does can someone tell me why?

CodePudding user response:

You can provide a default value for a known type, but you can't provide a default value for a deduced type like this. It's just not something the language supports.

You have to provide a default for the type and the value:

template<typename T, typename Cmp = std::less<>>
decltype(auto) find_median(T begin,
                           T end,
                           bool sorted = false,
                           Cmp comparison = {})
{
    // ...
}
  • Related