Ambiguity Resolution for Lambda Overload Using Unary Plus Operator
In C , overloading a function by providing multiple implementations with different parameter types allows for flexibility in code reuse. However, when attempting to call a function with a lambda expression, ambiguity can arise if the lambda can satisfy multiple overloads.
The Ambiguity Issue
Consider the following code snippet:
#include <functional> void foo(std::function<void()> f) { f(); } void foo(void (*f)()) { f(); } int main() { foo([](){}); // ambiguous }
The first call to foo with the lambda expression []() becomes ambiguous because the compiler cannot determine which overload to use. Both the std::function and the function pointer overloads are viable candidates.
Resolving Ambiguity with the Unary Plus Operator
The notation, in this case the unary plus operator, can be used to resolve this ambiguity. By placing the unary plus before the lambda expression, it forces a conversion to the function pointer type:
foo(+[](){});
This conversion makes the function pointer overload the exact match for the argument type, void (*)(), and eliminates the ambiguity.
The Unary Plus Operator
The unary plus operator defined in the C standard has the following property:
"The operand of the unary operator shall have arithmetic, unscoped enumeration, or pointer type and the result is the value of the argument."
In the case of a lambda, despite not having an arithmetic or pointer type, it can be converted to void (*)() due to the properties of its closure type. The closure type for a lambda has a non-explicit conversion function to a function pointer with the same parameter and return types as the lambda's function call operator.
Choosing the Function Pointer Overload
With the unary plus forcing the conversion to void (*)(), the second overload, void foo(void (*f)()), becomes an exact match in the overload resolution ranking. Since it is the only exact match, it is chosen unambiguously.
Alternative Approaches
Alternatively, to explicitly cast the lambda to the function pointer type to avoid ambiguity, one can use:
foo(static_cast<void (*)()>([](){}));
The above is the detailed content of How Can the Unary Plus Operator Resolve Ambiguity When Overloading Lambdas in C ?. For more information, please follow other related articles on the PHP Chinese website!