Scott Jones Scott Jones - 7 days ago 5
C++ Question

Null propagation operator in C++

Has anyone implemented a null propagation operator in C++, similar to that used in functional languages? I'm thinking of some clever template solution, possibly akin to the propagating behavior of operator->.

EDIT:
By request, a bit of fleshing out...

Let's suppose we have a chain of objects from a graph, like

foo->bar->baz
(sorry, Law of Demeter). Suppose any one of these could be null, and should be tested before dereferencing. Then the code suddenly becomes much more complicated:

if( !foo )
return nullptr;
if( !foo->bar )
return nullptr;
return foo->bar->baz;


I'd like to "factor out" the null checks with some kind of compact syntax like this:

foo?->bar?->baz // imaginary null-propagation syntax


Now, of course it doesn't have to look like that, just be nearly as compact. I suppose what's needed is a monad in C++, enabling the null test and a 'continuation'. It would be great to avoid macros and lambdas, but that's probably not possible. I could imagine overloading operator->() at each step and short-circuiting out if
this
was null. But that's very intrusive. An ideal solution would wrap each object in the chain.

Answer

At this stage in your design it might be a radical departure, but perhaps consider using the Null Object Pattern. Then you don't need any null checks at all.

Comments