Search code examples
c++templateslambdac++17default-parameters

Default lambda as templated parameter of a function


Consider the following code

template<bool b, typename T> void foo(const T& t = []() {}) {
  // implementation here
}

void bar() {
  foo<true>([&](){ /* implementation here */ }); // this compiles
  foo<true>(); // this doesn't compile
}

In the case that doesn't compile I get the following errors:

error C2672: 'foo': no matching overloaded function found
error C2783: 'void foo(const T&)': could not deduce template argument for 'T'

I think it's clear what I want to achieve: let foo be called with and without a client-provided lambda. The compiler is MSVC++2017 version 15.4.4 toolset v141.


Solution

  • The compiler uses the arguments passed to deduce the template type. If there's no arguments, then how would the compiler be able to deduce the template type?

    You can use overloading instead of default arguments here.

    The overloaded non-argument function can simply call the function with the "default" argument:

    template<bool b, typename T> void foo(const T& t) {
      // implementation here
    }
    
    template<bool b> void foo() {
      foo<b>([]() {});
    }