Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the value type of an iterator in a template declaration?

For this template declaration:

template <class Iterator>
typename std::iterator_traits<Iterator>::value_type Mean(Iterator begin, Iterator end);

I would like to simplify the value_type typename with a "using declaration" or typedef. So that it is a easier to read the return type. Is there a way to do this in the declaration?

Related posts
1
2

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can add an template alias like

template <typename Iterator>
using iterator_value_type_t = typename std::iterator_traits<Iterator>::value_type;

and then you can use that with your function like

template <class Iterator>
iterator_value_type_t<Iterator> Mean(Iterator begin, Iterator end);

If you want to allow specifying a custom return type then you can move the return type into the template parameter list like

template <class Iterator, 
          class ReturnType = typename std::iterator_traits<Iterator>::value_type>
ReturnType Mean(Iterator begin, Iterator end);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading