Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default lambda argument in template function

Tags:

c++

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";
  });
}
like image 444
fatdragon Avatar asked Mar 01 '23 16:03

fatdragon


1 Answers

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

like image 186
cigien Avatar answered Mar 16 '23 09:03

cigien