简体   繁体   中英

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

I have a template Node below for storing some data in an array. 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> . It seems that I will have to put ALL the attributes from Node to the specialized version for string. 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 ? 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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