C ++中的空传播运算符 [英] Null propagation operator in C++

查看:86
本文介绍了C ++中的空传播运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有人在C ++中实现了空传播运算符,类似于功能语言中使用的传播运算符?我正在考虑一些聪明的模板解决方案,可能类似于operator->的传播行为。

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

让我们假设我们有一个来自图的对象链,例如 foo-> bar-&b; baz (对不起,得墨meter耳法则)。假设其中任何一个可以为null,并且应在取消引用之前进行测试。然后,代码突然变得更加复杂:

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

现在,当然不必看起来像那样,只需紧凑即可。我想需要的是C ++中的monad,可以启用null测试和 continuation。最好避免使用宏和lambda,但这可能是不可能的。我可以想象如果 this 为null,则会在每个步骤中重载operator->()并短路。

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.

推荐答案

在设计的这个阶段,这可能是一个根本性的偏离,但也许可以考虑使用空对象模式。然后,您根本不需要任何null检查。

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.

这篇关于C ++中的空传播运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆