I want to default a lambda argument in a template function but it fails to compile. What am I missing?
template <typename F>
void foo(
  F f = [](){
          std::cout << "Hello!\n";
        }
) {
  f();
}
int main() {
  foo();  // 1. does not compile
  foo([](){ // 2. this is ok
    std::cout << "Hello!\n";
  });
}
                You can't deduce the template parameter of a function from the default function arguments. See this question for details on why this restriction is in place.
So you must provide a default template parameter yourself. Since you need both the type and the value of the lambda, a simple way to do this would be to write the lambda once, and then use it inside the function template.
auto lambda = []() 
              {
                 std::cout << "Bye!\n";
              };
        
template <typename F = decltype(lambda)>  // default parameter
void foo(F f = lambda)                    // default value  
{
  f();
}
Here's a demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With