Home > Backend Development > C++ > body text

How does the unary operator resolve ambiguity when calling a function with a lambda expression as an argument?

Patricia Arquette
Release: 2024-11-14 16:22:02
Original
323 people have browsed it

How does the unary   operator resolve ambiguity when calling a function with a lambda expression as an argument?

Resolving Ambiguous Overload with Unary Operator for Lambda Functions

In the provided code snippet:

void foo(std::function<void()> f) { f(); }
void foo(void (*f)()) { f(); }

int main()
{
    foo([]() {}); // ambiguous
    foo(+[]() {}); // resolves to function pointer overload
}
Copy after login

The first call to foo is ambiguous, failing to compile. This ambiguity arises from the fact that the lambda expression can be implicitly converted to both std::function and void (*f)().

To resolve this ambiguity, the unary operator is used before the lambda in the second call. The operator converts the lambda expression to a function pointer type, void (*)(), which matches the second overload exactly.

According to the C standard:

  • The unary operator converts the argument to its underlying type (arithmetic, enumeration, or pointer).
  • For lambda expressions, the conversion function in the closure type explicitly converts to a function pointer with the same parameter and return types.

Therefore, the expression []() {} results in a void (*)() function pointer, which unambiguously matches the second overload.

It's important to note that the lambda expression can also be explicitly cast to a function pointer type to avoid ambiguity:

foo((void (*)())([]() {}));
Copy after login

The above is the detailed content of How does the unary operator resolve ambiguity when calling a function with a lambda expression as an argument?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template