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))
.
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:
Note the parentheses around the returned expression. Without them, the return type is the type of the data member
first
instd::pair
, which has no reference qualification. With them, the return type has a&
sinceit->first
is an lvalue.