Home > Backend Development > C++ > body text

How to Resolve Ambiguity in Overloaded Functions When Passing Lambdas as Arguments in C ?

Linda Hamilton
Release: 2024-11-19 07:40:03
Original
939 people have browsed it

How to Resolve Ambiguity in Overloaded Functions When Passing Lambdas as Arguments in C  ?

Resolving Ambiguity in Overloaded Functions for Lambdas

In C , when calling a function with a lambda as an argument, ambiguity can arise if there are multiple overloads that match the lambda's type. This can lead to compilation errors.

Consider the following code:

#include <functional>

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

int main()
{
    foo([](){}); // ambiguous
}
Copy after login

In this code, there are two overloads of foo: one taking a std::function and one taking a function pointer. When calling foo with a lambda ([](){}), the compiler cannot determine which overload to call, causing an error.

To resolve this ambiguity, you can use the unary plus operator ( ) before the lambda, as shown below:

foo(+[](){}); // not ambiguous (calls the function pointer overload)
Copy after login

The plus operator forces the conversion of the lambda to a function pointer, enabling the second overload of foo to be matched exactly and called without ambiguity.

This behavior stems from the unary plus operator's ability to convert certain types, including lambdas, to function pointers. This conversion function is defined as follows:

The operand of the unary + operator shall have arithmetic, unscoped enumeration, or pointer type, and the result is the value of the argument.
Copy after login

Since the lambda's closure type has a conversion function to a function pointer, the unary plus operator converts the lambda to the desired function pointer type, allowing for exact matching in overload resolution.

The above is the detailed content of How to Resolve Ambiguity in Overloaded Functions When Passing Lambdas as Arguments in C ?. 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