【发布时间】:2012-11-16 22:04:57
【问题描述】:
我在下面有一个模板Node,用于在数组中存储一些数据。在添加之前,我想检查是否存在具有相同值的条目(我的插入逻辑需要它)。对于字符串类型,我想实现一个具体的比较方法。
template <class T> class Node
{
private:
short noOfEntries;
T data[MAX_VALUES];
public:
Node () { noOfEntries = 0; }
int Compare(int index, T *key);
int Insert(T *key);
};
template <class T>
int Node<T>::Compare(int index, T *key)
{
if(data[index] > *key)
return 1;
else if(data[index] == *key)
return 0;
return -1;
}
template <>
class Node <string> {
public:
int Compare(int index, string *key)
{
return (data[index].compare(*key));
}
};
这会产生错误,因为属性 'data' 和 'noOfEntries' 不在类 Node <string> 中。
看来我必须将 Node 中的所有属性都放到字符串的专用版本中。方法也一样。
有没有更好的方法让我只为 Node 定义一个插入方法,该方法将根据 T 的实际类型调用正确的 compare() 方法?我想避免重复方法。
【问题讨论】:
-
具有不同字符特征或分配器的字符串呢?
标签: c++ string templates generics