Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid to declare the same type two different times in function header and body when dealing with templates?

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.

like image 864
DarioP Avatar asked Jan 31 '26 03:01

DarioP


1 Answers

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

like image 119
Nikos Athanasiou Avatar answered Feb 01 '26 18:02

Nikos Athanasiou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!