I wrote this function that returns the mean of the values in the range delimited by two iterators:
template<class InputIterator>
typename std::decay<decltype(*std::declval<InputIterator>())>::type mean (InputIterator first, InputIterator last) {
return std::accumulate(first, last, typename std::decay<decltype(*std::declval<InputIterator>())>::type ()) / std::distance(first, last);
}
The value type, which is both used internally and returned, is deduced from the iterator. Since the syntax for the type deduction is quite heavy I was wondering if there is a way to avoid to use it twice.
I know that I may add a second template parameter and set its default to the value type, but I'm not convinced since one may specify a different value type and I would like to preclude this possibility.
You can use alias templates to form a generic typedef for yourType
template<class InIt>
using yourType = typename decay<decltype(*declval<InIt>())>::type;
template<class InIt>
yourType<InIt> mean(InIt first, InIt last)
{
return accumulate(first, last, yourType<InIt>()) / distance(first, last);
}
Live Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With