模板参数推导/替换失败,以lambda作为函数指针 [英] Template argument deduction/substitution failed with lambda as function pointer

查看:99
本文介绍了模板参数推导/替换失败,以lambda作为函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么在下面的代码中,编译器无法将lambda用作函数foo()的参数(模板参数推导/替换失败),而一个简单的函数却起作用:

I'm wondering why in the following code the compiler is unable to use lambda as the argument for function foo() (template argument deduction/substitution failed), while a simple function works:

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)

The intel compiler (version 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...))

有什么想法吗?

推荐答案

模板参数推论不考虑隐式转换.

类型推导不考虑隐式转换(上面列出的类型调整除外):这就是

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

You can convert the lambda to function pointer explicitly, e.g. you can use static_cast,

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

operator+

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

这篇关于模板参数推导/替换失败,以lambda作为函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆