The goal is to print each k,v pair in a map, using template:
template<typename K, typename V>
typedef std::map<K,V>::const_iterator MapIterator;
template<typename K, typename V>
void PrintMap(const std::map<K,V>& m) {
for (MapIterator iter = m.begin(); iter != m.end(); iter++) {
std::cout << "Key: " << iter->first << " "
<< "Values: " << iter->second << std::endl;
}
}
However, my compiler says that the expression iter->first could not be resolved, what's the problem?
EDIT: I should read compile errors at first, then trying to solve problems by tracing errors. Asking for help without thinking is not a good habit, thanks to @Oli Charlesworth.
error: template declaration of ‘typedef’
error: need ‘typename’ before ‘std::map<T1, T2>::const_iterator’ because ‘std::map<T1, T2>’ is a dependent scope
error: ‘MapIterator’ was not declared in this scope
error: expected ‘;’ before ‘iter’
error: ‘iter’ was not declared in this scope
COMPLEMENTS: The problem has been discussed in great detail in Where and why do I have to put the "template" and "typename" keywords?. According to @RiaD, there is a trivial solution to this problem as a complement.
template<typename K, typename V>
void PrintMap(const std::map<K,V>& m) {
typedef typename std::map<K,V>::const_iterator MapIterator;
for (MapIterator iter = m.begin(); iter != m.end(); iter++) {
std::cout << "Key: " << iter->first << " "
<< "Values: " << iter->second << std::endl;
}
}