Default lambda as templated parameter of a function

后端 未结 5 475
悲&欢浪女
悲&欢浪女 2021-01-22 02:07

Consider the following code

template void foo(const T& t = []() {}) {
  // implementation here
}

void bar() {
  foo([&         


        
5条回答
  •  别那么骄傲
    2021-01-22 02:26

    Default function arguments are not part of the template argument deduction process. To quote [temp.deduct.partial]/3:

    The types used to determine the ordering depend on the context in which the partial ordering is done:

    • In the context of a function call, the types used are those function parameter types for which the function call has arguments. 141

    141) Default arguments are not considered to be arguments in this context; they only become arguments after a function has been selected.

    That bullet and note indicate that since you didn't provide an argument for t in the call to foo, the type T cannot be deduced. The default lambda argument can only be taken into account if the function is selected to be called, not before.

    The solution, as all the others have noted, is to provide an overload without parameters, that will call the templated one with the default lambda you have in mind.

提交回复
热议问题