2012-11-16 81 views
3

我有一個模板Node用於在數組中存儲一些數據。添加之前我想檢查一個條目是否存在相同的值(我的插入邏輯需要它)。對於字符串類型,我想實現一個特定的方法進行比較。C++模板:爲特定數據類型創建專用函數

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

這使誤差作爲屬性「數據」和「noOfEntries」不在Node <string>類。 看來,我將不得不將所有屬性從節點放到字符串的專用版本。方法也一樣。

有沒有更好的方法,以便我將只有一個爲Node定義的插入方法,它將調用正確的compare()方法,具體取決於T的實際類型?我想避免重複的方法。

+0

不同字符特徵或分配器的字符串呢? –

回答

4

只是專注的一個成員:

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

更慣用的方式來做到這一點是使用比較策略模板參數,或者可能描述元素類型的默認比較策略的特點。

+0

這真棒。我非常感謝你幫助我:)你從哪裏學到的?我是一個新手,並想提高自己。 –

+0

我推薦「C++模板完整指南」。另請參閱我們的[權威圖書列表](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – sehe