我想知道为什么在下面的代码中编译器无法使用 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;
}
英特尔编译器(版本 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...))
有任何想法吗?
模板参数推导 https://en.cppreference.com/w/cpp/language/template_argument_deduction#Implicit_conversions不考虑隐式转换。
类型推导不考虑隐式转换(上面列出的类型调整除外):这就是过载解析 https://en.cppreference.com/w/cpp/language/overload_resolution,这会在稍后发生。
您可以将 lambda 显式转换为函数指针,例如您可以使用static_cast
,
foo(static_cast<int(*)(int)>([](int) { return 0; }));
or operator+ https://stackoverflow.com/q/18889028/3309790,
foo(+[](int) { return 0; });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)