4

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";
  });
}
fatdragon
  • 2,211
  • 4
  • 26
  • 43

1 Answers1

7

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

cigien
  • 57,834
  • 11
  • 73
  • 112