C#null coalescing运算符等效于c ++

C#null合并运算符是否有C ++等价物? 我在代码中进行了太多的空检查。 所以正在寻找一种减少空代码量的方法。

默认情况下,在C ++中没有办法执行此操作,但您可以编写一个:

在C#中? 运算符定义为

 a ?? b === (a != null ? a : b) 

所以,C ++方法看起来像

 Coalesce(a, b) // put your own types in, or make a template { return a != null ? a : b; } 

我刚发现了这个: ?? 运算符又是Null Coalescing运算符

您还可以使用?:运算符将它作为GNU扩展在C / C ++中使用:

 string pageTitle = getTitle() ?: "Default Title"; 

这个怎么样?

 #define IFNULL(a,b) ((a) == null ? (b) : (a)) 

使用模板和C ++ 11 lambda。 第一个参数(左侧)仅评估一次。 第二个参数(右侧)仅在第一个参数为false时进行评估(注意’if’和’?’将提供的表达式静态转换为bool,并且指针具有等效的’显式运算符bool()const’到’!= nullptr’)

 template TValue coalesce(TValue mainValue, TSpareEvaluator evaluateSpare) { return mainValue ? mainValue : evaluateSpare(); } 

使用示例

 void * const nonZeroPtr = reinterpret_cast(0xF); void * const otherNonZeroPtr = reinterpret_cast(0xA); std::cout << coalesce(nonZeroPtr, [&] () { std::cout << "Never called"; return otherNonZeroPtr; }) << "\n"; 

只需在控制台中打印“0xf”即可。 必须为rhs写一个lambda是一个小样板

 [&] () { return ; } 

但如果缺乏语言语法的支持,那么这是最好的。

只想扩展@Samuel Garcia的答案,通过推广模板并添加辅助宏来减少lambda样板:

 #include  namespace coalesce_impl { template auto coalesce(LHS lhs, RHS rhs) -> typename std::remove_reference::type&& { auto&& initialValue = lhs(); if (initialValue) return std::move(initialValue); else return std::move(rhs()); } template auto coalesce(LHS lhs, RHS rhs, RHSs ...rhss) -> typename std::remove_reference::type&& { auto&& initialValue = lhs(); if (initialValue) return std::move(initialValue); else return std::move(coalesce(rhs, rhss...)); } } #define COALESCE(x) (::coalesce_impl::coalesce([&](){ return ( x ); })) #define OR_ELSE ); }, [&](){ return ( 

使用宏,您可以:

 int* f(); int* g(); int* h(); int* x = COALESCE( f() OR_ELSE g() OR_ELSE h() ); 

我希望这有帮助。