考虑以下代码
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
}
在无法编译的情况下,我会收到以下错误:
error C2672: 'foo': no matching overloaded function found
error C2783: 'void foo(const T&)': could not deduce template argument for 'T'
我认为我想要实现的目标很明确:让 foo
在有和没有客户端提供的 lambda 的情况下被调用。编译器为MSVC++2017版本15.4.4工具集v141。
最佳答案
默认函数参数不是模板参数推导过程的一部分。引用[temp.deduct.partial]/3 :
The types used to determine the ordering depend on the context in which the partial ordering is done:
- In the context of a function call, the types used are those function parameter types for which the function call has arguments. 141
141) Default arguments are not considered to be arguments in this context; they only become arguments after a function has been selected.
该项目符号和注释表明,由于您没有在对 foo
的调用中为 t
提供参数,因此类型 T
不能被推导。只有在选择调用函数时才会考虑默认的 lambda 参数,而不是之前。
正如所有其他人所指出的那样,解决方案是提供一个不带参数的重载,它将使用您想到的默认 lambda 调用模板化的重载。
关于c++ - 默认 lambda 作为函数的模板化参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47495384/