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";
  });
}

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.