C# null coalescing operator equivalent for c++

前端 未结 7 1661
走了就别回头了
走了就别回头了 2020-12-09 16:02

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.

7条回答
  •  醉话见心
    2020-12-09 16:44

    Here are two macros to replicate the ?. and ?? operators respectively. They also safely eval operands only once:

    #define COACALL(a, b) ([&](){ auto val = (a); if (val) (val->b); }());
    #define COALESCE(a, b) ([&](){ auto val = (a); return ((val) == NULL ? (b) : (val)); }()) 
    

    Used like so:

    COACALL( goodPtr , sayHello() );
    COACALL( nullPtr , sayHello() );
    
    COALESCE( nullPtr, goodPtr )->sayHello();
    COALESCE( nullPtr, COALESCE( nullPtr, goodPtr ) )->sayHello();
    
    COACALL( COALESCE( nullPtr, goodPtr ), sayHello() );
    

提交回复
热议问题