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.
Using templates and C++11 lambdas. The first argument (left-hand side) is only evaluated once. The second argument (right-hand side) is only evaluated if the first is false (note that 'if' and '?' statically cast the provided expression to bool, and that pointers have 'explicit operator bool() const' that is equalivent to '!= nullptr')
template
TValue
coalesce(TValue mainValue, TSpareEvaluator evaluateSpare) {
return mainValue ? mainValue : evaluateSpare();
}
Example of use
void * const nonZeroPtr = reinterpret_cast(0xF);
void * const otherNonZeroPtr = reinterpret_cast(0xA);
std::cout << coalesce(nonZeroPtr, [&] () { std::cout << "Never called"; return otherNonZeroPtr; }) << "\n";
Will just print '0xf' in the console. Having to write a lambda for the rhs is a little bit of boilerplate
[&] () { return ; }
but it's the best that one can do if one lacks support by the language syntax.