引数がテンプレート化されたコンテナーであるテンプレート関数を記述するための形式 (ある場合) は何ですか?
たとえば、反復可能な任意のコンテナーで機能する一般的な合計を書きたいとします。以下のコードを考えると、例えば書く必要があります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;
}