Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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->.

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.

like image 938
Scott Jones Avatar asked Apr 29 '13 00:04

Scott Jones


1 Answers

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.

like image 122
Richard Walters Avatar answered Sep 21 '22 12:09

Richard Walters