我想定义一个通用函数来打印std::map
类似的内容。我最初的尝试是这样的功能:类似地图类型的C++模板专门化
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;
}
它工作正常。当我试图将此功能推广一步时,即使它适用于std::multimap
类型时,编译器变得生气。我尝试了几种方法,使std::map
通用的函数定义,如:
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;
}
没有成功。
我如何概括这个函数,就像我上面定义的那样?
为了更清楚起见,我已经定义了一个为此函数之前定义的类向量类定义的函数。它就像
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;
}
所以我想要实现它,使这个功能专门针对地图类。我在C++中很新,所以我不知道这种东西的确切名词。这被称为“模板专业化”吗?
地图实际上有四个模板参数,其中一些是默认的。 –
@BoPersson好点。它可能会解决模板别名可能,但也许不值得的麻烦。 – TemplateRex