Is there a C++ equivalent for C# null coalescing operator? I am doing too many null checks in my code. So was looking for a way to reduce the amount of null code.
Here are two macros to replicate the ?. and ?? operators respectively. They also safely eval operands only once:
#define COACALL(a, b) ([&](){ auto val = (a); if (val) (val->b); }());
#define COALESCE(a, b) ([&](){ auto val = (a); return ((val) == NULL ? (b) : (val)); }())
Used like so:
COACALL( goodPtr , sayHello() );
COACALL( nullPtr , sayHello() );
COALESCE( nullPtr, goodPtr )->sayHello();
COALESCE( nullPtr, COALESCE( nullPtr, goodPtr ) )->sayHello();
COACALL( COALESCE( nullPtr, goodPtr ), sayHello() );