1

I really don't understand why this code

#include <map>

template<typename T, typename U> std::ostream& operator<<(std::ostream& o,
        const std::map<T,U>& input)
{
    for (std::map<typename T,typename U>::iterator it=input.begin(); it!=input.end(); ++it)
    {
        o << it->first << " => " << it->second << '\n';
    }
    return o;
}

returns this compilation error:

error: wrong number of template arguments (1, should be 4)
error: provided for ‘template<class _Key, class _Tp, class _Compare, class _Alloc> class std::map’

can anyone help me please??

user1403546
  • 1,379
  • 1
  • 16
  • 32

1 Answers1

4

You should write typename before the iterator declaration and use const_iterator:

for (typename std::map<T,U>::const_iterator it=input.begin(); it!=input.end(); ++it

The argument of the operator << requires const objects. So elements of the map must be const. To achieve this one uses a const_iterator. The typename in the declaration of the iterator is required to indicate that the following expression is a nested template class depending on the types T and U.

See also this question: Making sense of arguments to a function template

Community
  • 1
  • 1
StefanW
  • 197
  • 1
  • 4