考虑下面的代码
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。
默认函数参数不是模板参数推导过程的一部分。去引用[温度扣除部分]/3:
用于确定排序的类型取决于上下文
完成部分排序:
- 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.
该项目符号和注释表明,由于您没有提供论据t
在通话中foo
, 方式T
无法推论。仅当选择调用该函数时(而不是之前)才可以考虑默认的 lambda 参数。
正如所有其他人所指出的,解决方案是提供一个不带参数的重载,它将使用您想到的默认 lambda 调用模板化的重载。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)