简体   繁体   中英

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

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?

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 = {})
{
    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM