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 }
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
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:
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 (*)())([]() {}));
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!