Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template argument deduction/substitution failed with lambda as function pointer

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;
}

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

Any ideas?

like image 999
krojew Avatar asked Jul 20 '18 06:07

krojew


1 Answers

Template argument deduction doesn't consider implicit conversion.

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

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

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

or operator+,

foo(+[](int) { return 0; });
like image 71
songyuanyao Avatar answered Oct 15 '22 06:10

songyuanyao