kro*_*jew 9 c++ lambda templates template-argument-deduction
我想知道为什么在下面的代码中编译器无法使用lambda作为函数foo()的参数(模板参数推导/替换失败),而一个简单的函数工作:
template<class ...Args>
void foo(int (*)(Args...))
{
}
int bar(int)
{
return 0;
}
int main() {
//foo([](int) { return 0; }); // error
foo(bar);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
intel编译器(版本18.0.3)
template.cxx(12): error: no instance of function template "foo" matches the argument list
argument types are: (lambda [](int)->int)
foo([](int) { return 0; }); // error
^
template.cxx(2): note: this candidate was rejected because at least one template argument could not be deduced
void foo(int (*)(Args...))
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
模板参数推导不考虑隐式转换.
类型推导不考虑隐式转换(上面列出的类型调整除外):这是重载解析的工作,稍后会发生.
您可以显式地将lambda转换为函数指针,例如
foo(static_cast<int(*)(int)>([](int) { return 0; }));
Run Code Online (Sandbox Code Playgroud)
要么
foo(+[](int) { return 0; });
Run Code Online (Sandbox Code Playgroud)