Decoding the Magical " " Operator: Understanding the " []{}" Lambda
In a perplexing observation, a lone " " prefix to a lambda expression in C miraculously enables its reassignment. This enigmatic sorcery prompted the question: why does the following code compile successfully?
int main() { auto test = +[]{}; // The "+" operator casts a lambda to a function pointer test = []{}; }
The answer lies in the obscure depths of the C standard. The " " triggers a conversion to a plain old function pointer for the lambda. The lambda, being non-capturing, inherently possesses a conversion function to a function pointer with an identical signature. This conversion function, as defined in the C standard, returns the address of a function that behaves identically to the lambda's function call operator.
The unary " " operator, when applied to the closure object generated by the lambda, engages a set of built-in overloads. One of these overloads accepts any pointer type and converts it to a function pointer. The closure type's conversion to a function pointer, the only candidate overloaded function, thus takes precedence.
Consequently, the type of "test" in "auto test = []{};" is deduced to be "void(*)()". This function pointer compatibility enables the assignment of a second lambda/closure object to "test" even though their closure types differ.
This knowledge unveils the secret behind the " []{}" lambda's success. By casting the lambda to a function pointer, it bypasses the restriction on redefining lambdas, unlocking the ability to assign a new lambda object.
The above is the detailed content of Why Does ` []{}` Enable Lambda Reassignment in C ?. For more information, please follow other related articles on the PHP Chinese website!