Ser*_*tch 2 c++ lambda templates default-parameters c++17
请考虑以下代码
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
}
Run Code Online (Sandbox Code Playgroud)
在不编译的情况下,我得到以下错误:
error C2672: 'foo': no matching overloaded function found
error C2783: 'void foo(const T&)': could not deduce template argument for 'T'
Run Code Online (Sandbox Code Playgroud)
我认为我想要实现的目标很明确:让我们foo在没有客户提供的lambda的情况下调用它.编译器是MSVC++ 2017版本15.4.4工具集v141.
默认函数参数不是模板参数推导过程的一部分.引用[temp.deduct.partial]/3:
用于确定排序的类型取决于完成部分排序的上下文:
- 在函数调用的上下文中,使用的类型是函数调用具有参数的函数参数类型. 141
141)在此上下文中,默认参数不被视为参数; 它们只在选择了一个函数后才成为参数.
该子弹和注释表明,由于您未t在调用中提供参数,因此无法推断出foo该类型T.如果选择调用该函数,则不能考虑默认的lambda参数,而不是之前.
正如所有其他人所指出的那样,解决方案是提供一个没有参数的重载,它将使用您想到的默认lambda调用模板化的.