您可以使用std::iterator_traits::value_type
:
typedef typename std::iterator_traits<Iter>::value_type value_type;
至於函數聲明和定義,在老派C++ 03的風格,你可以做到以下幾點:
template<typename Iter>
std::pair<typename std::iterator_traits<Iter>::value_type,
typename std::iterator_traits<Iter>::value_type>
summean(Iter first1, Iter last1)
{
typedef typename std::iterator_traits<Iter>::value_type value_type;
value_type sum = std::accumulate(first1, last1, value_type());
value_type mean = sum/(last1-first1);
return std::make_pair(sum, mean);
}
而且,由於C + +11您可以使用decltype
和追蹤返回類型使其不那麼冗長:
template<typename Iter>
auto summean(Iter first1, Iter last1)->decltype(std::make_tuple(*first1, *first))
{
using value_type = typename std::iterator_traits<Iter>::value_type;
value_type sum = std::accumulate(first1, last1, value_type());
value_type mean = sum/(last1-first1);
return make_tuple(sum, mean);
}