27

C# null 合体演算子に相当する C++ はありますか? コードで null チェックを実行しすぎています。そのため、null コードの量を減らす方法を探していました。

4

8 に答える 8

14

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;
}
于 2009-11-23T19:34:20.143 に答える
4

テンプレートを一般化し、ヘルパー マクロを追加してラムダ ボイラープレートを削減することで、@Samuel Garcia の回答を拡張したいだけです。

#include <utility>

namespace coalesce_impl
{
    template<typename LHS, typename RHS>
    auto coalesce(LHS lhs, RHS rhs) ->
        typename std::remove_reference<decltype(lhs())>::type&&
    {
        auto&& initialValue = lhs();
        if (initialValue)
            return std::move(initialValue);
        else
            return std::move(rhs());
    }

    template<typename LHS, typename RHS, typename ...RHSs>
    auto coalesce(LHS lhs, RHS rhs, RHSs ...rhss) ->
        typename std::remove_reference<decltype(lhs())>::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() );

これが役立つことを願っています。

于 2017-04-26T05:27:28.587 に答える
1

これはどう?

#define IFNULL(a,b) ((a) == null ? (b) : (a))
于 2009-11-23T19:34:59.580 に答える