I want to define a generic function for printing contents of std::map like types. My initial attempt is a function like this:
template <class K, class V>
inline void PrintCollection(const std::map<K,V>& map,
const char* separator="\n",
const char* arrow="->",
const char* optcstr="") {
typedef typename std::map<K,V>::const_iterator iter_type;
std::cout << optcstr;
for (iter_type begin = map.begin(), it = begin, end = map.end();
it != end; ++it) {
if (it != begin) {
std::cout << separator;
}
std::cout << it->first << arrow << it->second;
}
std::cout << std::endl;
}
which works fine. When I try to generalize this function one more step, i.e. make it work for std::multimap type, compiler becomes angry. I tried several ways to make std::map generic in the function definition, such as:
template <class M, class K, class V>
inline void PrintCollection(const M<K,V>& map,
const char* separator="\n",
const char* arrow="->",
const char* optcstr="") {
typedef typename M<K,V>::const_iterator iter_type;
std::cout << optcstr;
for (iter_type begin = map.begin(), it = begin, end = map.end();
it != end; ++it) {
if (it != begin) {
std::cout << separator;
}
std::cout << it->first << arrow << it->second;
}
std::cout << std::endl;
}
with no success.
How can I generalize this function as I defined above?
To be more clear, I have already a function defined for vector-like classes defined before this function. It is like
template <class T>
inline void PrintCollection(const T& collection,
const char* separator="\n",
const char* optcstr="") {
typedef typename T::const_iterator iter_type;
std::cout << optcstr;
for (iter_type begin = collection.begin(), it = begin, end = collection.end();
it != end;
++it) {
if (it != begin) {
std::cout << separator;
}
std::cout << *it;
}
std::cout << std::endl;
}
So what I want to achieve it to make this function specialized to map-like classes. I’m pretty new in C++, so I don’t know the exact term for this kind of stuff. Is this called “template specialization”?
Do it like the stdlib does and use iterators in your algorithm interfaces. This is the most generic solution.