C# null coalescing operator equivalent for c++

前端 未结 7 1657
走了就别回头了
走了就别回头了 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 17:01

    Just want to expand @Samuel Garcia's answer by generalising the template and adding helper macros to cut down on lambda boilerplate:

    #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 (
    

    Using the macros, you can just:

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

    I hope this helps.

提交回复
热议问题