C# null coalescing operator equivalent for c++

前端 未结 7 1656
走了就别回头了
走了就别回头了 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:46

    Using templates and C++11 lambdas. The first argument (left-hand side) is only evaluated once. The second argument (right-hand side) is only evaluated if the first is false (note that 'if' and '?' statically cast the provided expression to bool, and that pointers have 'explicit operator bool() const' that is equalivent to '!= nullptr')

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

    Example of use

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

    Will just print '0xf' in the console. Having to write a lambda for the rhs is a little bit of boilerplate

    [&] () { return ; }
    

    but it's the best that one can do if one lacks support by the language syntax.

提交回复
热议问题