模板参数 deduction/substitution 失败,lambda 作为函数指针

Template argument deduction/substitution failed with lambda as function pointer

我想知道为什么在下面的代码中编译器无法使用 lambda 作为函数 foo() 的参数(模板参数 deduction/substitution 失败),而一个简单的函数可以工作:

template<class ...Args>
void foo(int (*)(Args...))
{
}

int bar(int)
{
    return 0;
}

int main() {
    //foo([](int) { return 0; }); // error
    foo(bar);
    return 0;
}

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...))

有什么想法吗?

Template argument deduction 不考虑隐式转换。

Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.

您可以将 lambda 显式转换为函数指针,例如你可以使用 static_cast,

foo(static_cast<int(*)(int)>([](int) { return 0; }));

operator+,

foo(+[](int) { return 0; });