3 ms·
The ternary operator is indeed special as it (is the only one AFAIK that) introduces in the language some type constraints between the two result branches, that
by s_gourichon 7y ago
The ternary operator is indeed special as it (is the only one AFAIK that) introduces in the language some type constraints between the two result branches, that affect the way one or the other is interpreted.
A similar trick in C++ is explained on https://www.artima.com/cppsource/foreach2.html https://www.artima.com/cppsource/foreach2.html and allows to return the type of an expression without evaluating it.
From the link:
> You may be thinking this is needlessly convoluted. After all, couldn't we just use encode_type(container) without the conditional operator and get the same result? No, because that would have caused container to be evaluated. With the conditional operator, only one branch of the condition is ever executed. In this case, since the condition is always true, the first branch will always be taken. The second branch is "dead code"—it will never execute—yet it extends a ghostly finger into the land of the living and exerts its influence on the conditional expression's type. Spooky!
- smitty1e 7y agoThat's just C++ wishing that it could have a type system closer to Haskell's.
- saagarjha 7y agoQt apparently does something similar to implement Q_FOREACH: https://stackoverflow.com/a/10522384/5230900 https://stackoverflow.com/a/10522384/5230900
- likeliv 7y agoThat was pre-c++11. Now using C++11, it is much simpler (using 'auto'). And the C++17 version is even simpler https://code.woboq.org/qt5/qtbase/src/corelib/global/qglobal.h.html#1085-1107 https://code.woboq.org/qt5/qtbase/src/corelib/global/qglobal...
- aardvark179 7y agoThat sort of operator is often tough, just look at section 15.25 in the Java language specification (https://docs.oracle.com/javase/specs/jls/se13/html/jls-15.html#jls-15.25 https://docs.oracle.com/javase/specs/jls/se13/html/jls-15.ht...) in the type of such expressions.
- MauranKilom 7y agoFor those wondering (like I did) "But there already is a C++ facility whose sole purpose is determining the type of an expression [or entity] without evaluation it?" decltype() only exists since C++11 (and the above article is from 2006). https://en.cppreference.com/w/cpp/language/decltype https://en.cppreference.com/w/cpp/language/decltype