我有一个实现红黑树的模板类,它的行为有点像(伪) map 。伪映射,因为它不会存储键,只会存储值,键嵌入在值中。它需要 operator== 和 operator< 重载来针对任意键测试存储的值并相互对抗(使用嵌入式键)。例如
struct Val
{
//some actual data
std::string key;
bool operator==(const Val &val) { return this->key == val.key; }
bool opeartor==(const std::string &str) { return this->key == str; }
bool opeartor<(const Val &val) { return this->key < val.key; }
bool opeartor<(const std::string &str) { return this->key < str; }
};
这种“值(value)”将进入这个模板类:
template<typename T>
class Map
{
struct Node
{
//...
T data;
};
public:
//..
template<typename K> T value(const K &key) const
{
Node *it;
//...
if(it->data == key)
//...
int dir = (it->data < key);
//...
}
};
然而,当行if(it->data == key)
检查很好(我还没有使用该类(class))第二个 int dir = (it->data < key);
没有错误“模板参数列表中的解析错误”。奇怪的是,如果我将比较更改为 <=
它编译得很好。但是那时我已经知道它不相等(第一次检查 <
就可以了。
我该如何解决它以及为什么它提示一个运算符(operator)而不是其他运算符(operator)?
最佳答案
T.C.已经在评论中发布了答案,所以我将重复它作为答案。该行为是由于 GCC 中长期存在的错误造成的 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=10200当一个人对命名不是很有创意并且在类中有一堆相同的名字时就会表现出来(在这种情况下,嵌套类中名为 data
的成员变量和名为 data< 的成员方法
在父类(super class)中)。
关于c++ - 小于模板参数的比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34113366/