Deducing constness of a pair member in a template return type

109 views Asked by At

Assume I have an iterator referencing a std::pair. It might point into a map, so first_type would be const. But it might also be a vector of pairs, and first_type is mutable. How do I define a function that returns a reference to the first of that pair?

What I have tried is this:

template<typename TPairIter>
typename std::iterator_traits<TPairIter>::value_type::first_type& first_of_pair_func(TPairIter it) 
{return it->first;}

However, this gives errors for my code when first_type is const. Apparently, std::iterator_traits<TPairIter>::value_type::first_type strips the const.

Note: Other code needs to deduce the return type from this function by doing decltype(first_of_pair_func(it)).

1

There are 1 answers

2
sbi On

Of course, after having battled this since 24hrs ago, I figured out the solution within 5 minutes after posting the question here. :-/

This does the trick:

template<typename TPairIter>
auto first_of_pair_func(TPairIter it) -> decltype(auto) {return (it->first);}

Note the parentheses around the returned expression. Without them, the return type is the type of the data member first in std::pair, which has no reference qualification. With them, the return type has a & since it->first is an lvalue.