1


[更新された要件に応じた質問の更新]
最初に非 null 要素を返すか、例外をスローする次の関数を実装しました。
また、'max'、'min'、'pair' などのより古典的で短い名前を考えてもらえますか?

template <typename T>
T select_first_not_empty( const T& a, const T&b )
{
    static T null = T();

    if ( a == null && b == null )
        throw std::runtime_error( "null" );

    return
        a != null ? a : b;
}

int main()
{
    const int a1 = 2;
    const int b1 = 0;

    const int* a2 = 0;
    const int* b2 = new int(5);

    const std::string a3 = "";
    const std::string b3 = "";

    std::cout << select_first_not_empty( a1, b1 ) << std::endl;
    std::cout << select_first_not_empty( a2, b2 ) << std::endl;
    std::cout << select_first_not_empty( a3, b3 ) << std::endl;

    return 0;
}
4

3 に答える 3

3

あなたは次にやってみることができます

template < typename T >
T get_valuable( const T& firstValue, 
                const T& alternateValue, 
                const T& zerroValue = T() )
{
    return firstValue != zerroValue ? firstValue : alternateValue;
}

// usage
char *str = "Something"; // sometimes can be NULL
std::string str2 ( get_valuable( str,  "" ) );

// your function
template <typename T>
T select_first_not_empty( const T& a, 
                          const T& b, 
                          const T& zerroValue = T() )
{
    const T result = get_valuable( a, b, zerroValue );
    if ( result == zerroValue )
    {
        throw std::runtime_error( "null" );
    }
    return result;
}
于 2009-03-10T19:11:37.737 に答える
2

C# には、同様に機能する組み込みの operator??があり、私はこれを合体と呼んでいます。

Perl の||(短絡論理 OR) 演算子にも同様の機能があります: 0 または 1 を返す代わりに、true と評価される最初の引数の値を返します。

0 || 7

1 ではなく 7 を返すかtrue、C\C++ または C# プログラマーが期待するとおりです。

C++ に組み込まれているこれに最も近いのは、find_if アルゴリズムです。

vector<int> vec;
vec.push_back(0);
vec.push_back(0);
vec.push_back(7);

vector<int>::iterator first_non_0 = 
    find_if(vec.begin(), vec.end(), bind2nd(not_equal_to<int>(), 0));
于 2009-03-10T19:09:21.283 に答える
2

T の ctor が重要なことを行う場合、「select_first_not_empty」を介して毎回 3 回実行しているように見えます。

より良い名前を探している場合、オラクルは似たようなものを「COALESCE」と呼んでいます。

しかし、何がポイントなのかわかりません。何かが設定されているかどうかを本当に知りたい場合は、参照ではなく null 許容ポインターを使用します。「NULL」は、0 や「」などの帯域内値を使用するよりも、変数を設定しないという意図を示すはるかに優れた指標です。

于 2009-03-10T19:00:22.473 に答える