C++ c++;模板:为特定数据类型创建专用函数

C++ c++;模板:为特定数据类型创建专用函数,c++,string,templates,generics,C++,String,Templates,Generics,我在下面有一个模板节点,用于在数组中存储一些数据。在添加之前,我想检查一个条目是否具有相同的值(我的插入逻辑需要它)。对于字符串类型,我想实现一个特定的比较方法 template <class T> class Node { private: short noOfEntries; T data[MAX_VALUES]; public: Node () { noOfEntries = 0; } int Compare(int index, T *key)

我在下面有一个模板
节点
,用于在数组中存储一些数据。在添加之前,我想检查一个条目是否具有相同的值(我的插入逻辑需要它)。对于字符串类型,我想实现一个特定的比较方法

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));
    }
};
模板类节点
{
私人:
短午间;
T数据[最大值];
公众:
节点(){noOfEntries=0;}
int比较(int索引,T*键);
插入整数(T*键);
};
模板
int节点::比较(int索引,T*键)
{
if(数据[索引]>*键)
返回1;
else if(数据[索引]==*键)
返回0;
返回-1;
}
模板
类节点{
公众:
整数比较(整数索引,字符串*键)
{
返回(数据[索引]。比较(*键));
}
};
这会产生错误,因为属性“data”和“noOfEntries”不在类
节点中。
似乎我必须将节点中的所有属性都放到字符串的专用版本中。方法也是一样


有没有更好的方法可以让我只为节点定义一个insert方法,根据T的实际类型调用正确的compare()方法?我希望避免方法的重复。

只需专门化一个成员:

template <> int Node<std::string>::Compare(int index, std::string *key)
    {
        return (data[index].compare(*key));
    }
模板int节点::比较(int索引,std::string*键)
{
返回(数据[索引]。比较(*键));
}

更惯用的方法是使用比较策略模板参数,或者可能是描述元素类型的默认比较策略的traits。

这太棒了。我非常感谢你帮助我:)你是从哪里学来的?我是一个新手,希望提高自己。我推荐“C++模板完整指南”。另请参阅我们的关于具有不同字符特征或分配器的字符串的内容?