所以我试图创建一个比较两个迭代器的函数,但我不确定如何适本地使用模板。 类(class)
template<typename Key_T, typename Mapped_T>
class Map{...}
自由函数
bool operator==(const Map::Iterator &iter1, const Map::Iterator &iter2) {
return (*(iter1.ref->key) == *(iter2.ref->key)) ? true : false; }
我收到这个错误
error: invalid use of template-name ‘cs540::Map’ without an argument list
然后我试了一下
template<typename Key_T, typename Mapped_T>
bool operator==(const Map<Key_T,Mapped_T>::Iterator &iter1, const Map<Key_T,Mapped_T>::Iterator &iter2) {...}
我得到了这个错误
error: need ‘typename’ before ‘cs540::Map<Key_T,
Mapped_T>::Iterator’ because ‘cs540::Map<Key_T, Mapped_T>’ is a dependent scope
最佳答案
错误消息告诉您需要告诉编译器 Map<Key_T,Mapped_T>::Iterator
是一种类型,写成typename
在它前面 - 即
template<typename Key_T, typename Mapped_T>
bool operator==(const typename Map<Key_T,Mapped_T>::Iterator &iter1,
const typename Map<Key_T,Mapped_T>::Iterator &iter2) { ...}
参见 Where and why do I have to put the "template" and "typename" keywords?了解为什么需要这样做。
但这也不适合你。 ::
左侧的所有内容是 non-deduced context ;为了使运算符函数模板可用,编译器必须能够从调用中推导出模板参数,但当模板参数仅出现在非推导上下文中时,它不能这样做。结果是 Key_T
和 Mapped_T
永远无法推导出,operator==
永远不会被使用。
您的设计似乎符合
template<typename Key_T, typename Mapped_T>
class Map{
class Iterator {
// ...
};
// ...
};
通常的做法是定义一个非模板friend
operator==
在Iterator
里面定义,即
template<typename Key_T, typename Mapped_T>
class Map{
class Iterator {
// ...
friend bool operator==(Iterator iter1, Iterator iter2) {
return /* ... */;
}
};
// ...
};
一种可能的替代方法是制作 Iterator
在 Map
之外有自己的类模板:
template<typename Key_T, typename Mapped_T>
class MapIterator {
// ...
};
template<typename Key_T, typename Mapped_T>
class Map{
using Iterator = MapIterator<Key_T, Mapped_T>;
};
现在你可以写了
template<typename Key_T, typename Mapped_T>
bool operator==(MapIterator<Key_T, Mapped_T> iter1, MapIterator<Key_T, Mapped_T> iter2) {
return /* ... */;
}
作为Key_T
和 Mapped_T
现在可以正确推导。
关于c++ - 使用采用模板化迭代器的自由函数重载 operator==,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29114957/