简体   繁体   English

c ++ template:为特定数据类型创建专用函数

[英]c++ template: Create a specialized function for a specific data type

I have a template Node below for storing some data in an array. 我在下面有一个模板Node ,用于在数组中存储一些数据。 Before adding I want to check if an entry is present with the same value (my insert logic needs it). 在添加之前,我想检查条目是否存在具有相同的值(我的插入逻辑需要它)。 For string type, i want to implement a specific method for comparison. 对于字符串类型,我想实现一个特定的比较方法。

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));
    }
};

This gives error as the attributes 'data' and 'noOfEntries' are not in class Node <string> . 这会产生错误,因为属性'data'和'noOfEntries'不在Node <string> It seems that I will have to put ALL the attributes from Node to the specialized version for string. 似乎我必须将Node的所有属性都放到字符串的专用版本中。 Same thing for methods too. 方法也是如此。

Is there a better way so that I will have just one insert method defined for Node which will invoke correct compare() method depending on the actual type of T ? 有没有更好的方法,以便我只有一个为Node定义的插入方法,它将调用正确的compare()方法,具体取决于T的实际类型? I want to avoid duplication of the methods. 我想避免重复这些方法。

Just specialize the one member: 只专注一个成员:

template <> int Node<std::string>::Compare(int index, std::string *key)
    {
        return (data[index].compare(*key));
    }

A more idiomatic way to do this would be to use a comparison policy template argument, or possibly a traits describing the default comparison policy for the element type. 更常用的方法是使用比较策略模板参数,或者可能使用描述元素类型的默认比较策略的特征。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM