2

、のC++11可変個引数バージョンの実装について考察する必要がありstd::minますstd::max。これが私の2つの選択肢です。ここでは、std::min次のstd::maxように置き換えるだけで同様に実装されstd::minますstd::max

/*! Multi-Type Minimum of \p a. */
template <LessThanComparable T> const T & multi_type_min (const T & a) { return a; } // template termination
/*! Multi-Type Minimum of \p a and \p args. */
template <class T, class ... R >
//requires SameType <T , Args >...
T multi_type_min(const T & a, const R &... b)
{
    return std::min(a, multi_type_min(b...));
}

/*! Minimum of \p a. */
template <LessThanComparable T> const T & common_type_min(const T & a) { return a; } // template termination
/*! Minimum of \p a and \p args. */
template <class T, class ... R, class C = typename boost::common_type<T, R...>::type >
C common_type_min(const T & a, const R &... b)
{
    return std::min(static_cast<C>(a), static_cast<C>(common_type_min(b...)));
}

重要な質問は、必要かcommon_type_minどうかです。これにより、min()を1つの引数で呼び出すことができることに注意してください。これは混乱や問題を引き起こす可能性がありますか?

4

1 に答える 1

2

2つのパラメータで停止するまで再帰するように書くことはできませんか?

これは(テストされていない)スニペットです:

/*! Multi-Type Minimum of \p a and \p args. */
template <class T, class U >
//requires SameType <T , U >...
T multi_type_min(const T & a, const U & b)
{
    return std::min(a, b);
}

/*! Multi-Type Minimum of \p a and \p args. */
template <class T, class U, class ... R >
//requires SameType <T , U, Args >...
T multi_type_min(const T & a, const U & b, const R &... c)
{
    return std::min(a, multi_type_min(b, c...));
}

common_type_min複数の一般的なタイプがある場合、バリアントが必要だと思います。shortlong値の比較を検討してください。タイプの昇格のため、は比較のためshortに に変換されます。longただし、一部のアプリケーションの制約または不変条件により、両方の値を で表すことができることがわかる場合がありますshort。この場合、 が必要になる場合がありますcommon_type_min<short>(a,b)

于 2011-09-24T15:21:31.153 に答える