3

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.

Tejas Patil
  • 6,149
  • 1
  • 23
  • 38

1 Answers1

4

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.

sehe
  • 374,641
  • 47
  • 450
  • 633
  • This is awesome. I am extremely thankful to you for helping me out :) Where did you learn this from ? I am a newbie and would like to improve myself. – Tejas Patil Nov 16 '12 at 22:29
  • I recommend "C++ Templates The Complete Guide". See also our [definitive book list](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – sehe Nov 16 '12 at 22:42