1

引数がテンプレート化されたコンテナーであるテンプレート関数を記述するための形式 (ある場合) は何ですか?

たとえば、反復可能な任意のコンテナーで機能する一般的な合計を書きたいとします。以下のコードを考えると、例えば書く必要がありますsum<int>(myInts)sum(myInts)myInts に含まれる型から型を推測するだけでよいと思います。

/**
 @brief  Summation for iterable containers of numerical type
 @tparam cN                         Numerical type (that can be summed)
 @param[in]  container              container containing the values, e.g. a vector of doubles
 @param[out] total                  The sum (i.e. total)
 */
template<typename N, typename cN>
N sum(cN container) {
    N total;
    for (N& value : container) {
        total += value;
    }
    return total;
}
4

2 に答える 2

3

私はこのような関数を書きます

template<typename IT1>
typename std::iterator_traits<IT1>::value_type //or decltype!
function(IT1 first, const IT1 last)
{
    while(first != last)
    {
        //your stuff here auto and decltype is your friend.
        ++first;
    }
    return //whatever
}

このようにして、ostream イテレーターやディレクトリ イテレーターなど、単なるコンテナー以外でも機能します。

のように電話する

function(std::begin(container), std::end(container));
于 2012-04-04T16:49:31.077 に答える
0

これは、面倒な場合でも、C++11でトリックを実行できます。

template <typename C>
auto sum( C const & container ) 
     -> std::decay<decltype( *std::begin(container) )>::type

もう1つのオプションは、accumulateと同じ構造を使用することです。呼び出し元に初期値を含む追加の引数を渡してもらい、それを使用して式の結果を制御します。

template<typename N, typename cN>
N sum(cN container, N initial_value = N() )

(デフォルト値を指定することにより、ユーザーは値を使用して呼び出すか、テンプレート引数を指定するかを決定できますが、これにはタイプNがデフォルトで構成可能である必要があります)

于 2012-04-04T16:53:00.657 に答える