C++中匿名函数前的一元运算符‘+’作用解析
+ to a lambda fix Visual C++ compatibility here? Great question! Let's unpack what that unary + operator is doing, and why it's needed for Visual C++ even though Clang accepts the code without it.
First, a quick recap on lambdas
A capture-less lambda (like your anonym1 and anonym2, which don't capture any variables from the surrounding scope) has a special property in C++: it can be implicitly converted to a function pointer matching its signature. However, even if two lambdas have identical code and signatures, each one is a unique, compiler-generated anonymous closure type. That's the key detail here.
The problem with the ternary operator (?:)
The ternary operator requires that its two result expressions are either:
- The exact same type, or
- Implicitly convertible to a common shared type.
When you write:
auto anonymSel = x > y ? anonym1 : anonym2;
anonym1 and anonym2 are two distinct closure types. Clang (and GCC) are smart enough to recognize both can be converted to the same function pointer type (float(*)(float, float)), so they automatically perform that conversion to resolve the type mismatch.
Older versions of Visual C++ don't handle this implicit conversion in the ternary operator context. It sees two different closure types and throws a compilation error, because it can't deduce a common type on its own.
What the + operator does
The unary + operator triggers an implicit conversion of the capture-less lambda to its corresponding function pointer. Here's why:
- The unary
+works with expressions that can be converted to arithmetic types or pointer types. Since a capture-less lambda is convertible to a function pointer, applying+forces that conversion immediately. - So
+anonym1becomes afloat(*)(float, float)function pointer, and+anonym2is also the exact same function pointer type.
Now the ternary operator has two expressions of identical type, so Visual C++ (and all other compilers) can resolve anonymSel's type without any issues.
To sum up
- The
+isn't changing the functionality of the code—it's just ensuring that both branches of the ternary operator resolve to the same function pointer type explicitly (via implicit conversion triggered by+). - Clang/GCC handle the type conversion automatically in this scenario, but older Visual C++ versions need a little nudge to avoid a type mismatch error.
内容的提问来源于stack exchange,提问作者Tanmay

