私は通常整数を返す関数を持っていますが、値の意味が違うかもしれないので、それらを強く型付けしたいと思います。お金と時間は、テンプレート関数からさまざまな型を条件付きで返すための正しいアプローチ
struct Money {
uint32_t value;
}
のように簡略化されます。関数は、ブールパラメータに応じてMoneyまたはTimeのいずれかを返します。今コンパイラが異なる戻り値の型のために文句を言うだろう
template <typename T> T getValue(bool mode) {
Money money;
Time time;
...
if (mode == ModeMoney) {
money = something * 2;//get it from somewhere - irrelevant for the example
return money;
}
if (mode == ModeTime) {
time = something * 100;
return time;
}
}
ので、私は値そのものを返すために特化したテンプレート機能を追加します:それは次のようになりましょう
template <> Money variableValue<Money>(something) { return something * 2 };
template <> Time variableValue<Time>(something) { return something * 100};
これはブール値をドロップすることができますparam on invocationとmain関数は次のように変更されます:
template <typename T> T getValue(bool mode) {
....//calculation of *something* is the same, we only need different output from the function
return variableValue<T>(something);
}
これは良いアプローチですか?
関数のロジックと戻り値の型が異なる場合は、2つの関数に分割してみましょう。 –
ユースケースとは何ですか? 'getValue'の使い方によっては、もっと良いかもしれないいくつかの選択肢があります。 – wasthishelpful
私が投稿した例は非常に単純化されており、混乱の元になるかもしれません。ロジックは実際には同じですが、2つの関数を書くと、ロジックが2つの異なる出力で複製されます – estoy