The binary variant of ternary operator "Q ? T : F"
is created by leaving out term 'T'
, which results in "A ? : B"
. This operator is often called "Elvis Operator" because ?:
reminds people to an emoticon of singer Elvis Presley.
Usually the operator chooses 'A'
in the case that 'A'
can be interpreted as something like not null, not nulled or true
in any means. Otherwise it selects 'B'
. Due to the type-safe approach of ALib Expressions , the type of 'A'
and 'B'
must be equal, or at least an auto-cast has to exist that casts the types to a pair of equal types.
This built-in compiler plug-in covers the operator for virtually any type, including custom ones. The implementation invokes box-function FIsTrue on term 'A'
and chooses 'A'
if the interface returned true
, otherwise it chooses 'B'
.
Often, the elvis operator is used with strings. Because the default implementation of boxing interface FIsTrue returns true
if the boxed value is an array type and the array length is not zero, with strings given (which are arrays of characters) only empty strings evaluate to false
. This way the expression:
"" ?: "Elvis"
rightfully evaluates to string "Elvis".
With this default implementation, it should be very seldom needed to define a custom Elvis-Operator for custom types.
Definition at line 45 of file elvisoperator.hpp.
#include <elvisoperator.hpp>
Public Method Index: | |
ALIB_API | ElvisOperator (Compiler &compiler) |
virtual | ~ElvisOperator () override |
virtual ALIB_API bool | TryCompilation (CIBinaryOp &ciBinaryOp) override |
Public Method Index: inherited from CompilerPlugin | |
CompilerPlugin (const NString &name, Compiler &compiler) | |
virtual | ~CompilerPlugin () |
virtual bool | TryCompilation (CIAutoCast &ciAutoCast) |
virtual bool | TryCompilation (CIFunction &ciFunction) |
virtual bool | TryCompilation (CIUnaryOp &ciUnaryOp) |
Additional Inherited Members | |
Public Field Index: inherited from CompilerPlugin | |
Compiler & | Cmplr |
const NString | Name |
ALIB_API ElvisOperator | ( | Compiler & | compiler | ) |
Constructor.
compiler | The compiler we will get attached to. |
|
inlineoverridevirtual |
|
overridevirtual |
Compiles binary elvis operator A ?: B
if terms 'A'
and 'B'
share the same type.
[in,out] | ciBinaryOp | The compilation info struct. |
true
if an entry was found. false
otherwise. Reimplemented from CompilerPlugin.