14

std::function<double()>ラムダ式に割り当てています。このスニペットは機能します

if(fn_type==exponential)
    k.*variable = [=,&k](){ return initial*exp(-k.kstep*par); };
else
    k.*variable = [=,&k](){ return initial*pow(k.kstep, par); };

一方、三項演算子を使用したい場合

k.*variable = (fn_type==exponential ? [=,&k](){ return initial*exp(-k.kstep*par); } : [=,&k](){ return initial*pow(k.kstep, par); });

次のエラーが発生します。

error: no match for ternary ‘operator?:’ in <awfully long template error, because this whole thing is in a class defined in a function...>

これはgccのバグですか(4.7.2を使用しています)?そうでなければ、なぜ標準にこの制限があるのですか?

4

2 に答える 2

19

条件演算子の2番目と3番目のオペランドは同じ型であるか、コンパイラーが理解できるように両方を変換できる共通の型が存在する必要があります。コンパイラーが考慮する変換はほんの一握りです。

2つのラムダ式には異なるタイプがあり、両方を変換できる共通のタイプはありません(std::function<double()>有効なターゲットタイプが無限に存在する可能性があるため、のようなユーザー定義タイプへの変換は考慮できません)。

各オペランドを直接次のように変換できますstd::function<double()>

k.*variable = fn_type==exponential
    ? std::function<double()>([=,&k](){ return initial*exp(-k.kstep*par); })
    : std::function<double()>([=,&k](){ return initial*pow(k.kstep, par); });

しかし、実際には、if/を使用するとよりクリーンになりelseます。

于 2012-10-17T19:43:21.437 に答える
-1

また、この問題に直面しました-コンパイルされません!

「if/else」がうまくいかない場合は、自動型推定機能をオンにします。

    auto memcpy_traits = 
        [&](uint8_t* line_dst, const uint8_t* curr_src, const size_t bytes_to_copy) {
            std::memcpy(line_dst, curr_src, bytes_to_copy);
            line_dst += bytes_to_copy;
            curr_src += bytes_to_copy;
    }
    :
     [&](uint8_t* line_dst, const uint8_t* curr_src, const size_t bytes_to_copy) {
     std::memcpy(line_dst, curr_src, bytes_to_copy);
     line_dst += bytes_to_copy;
     curr_src += bytes_to_copy;
     };
于 2019-10-18T12:00:05.450 に答える