簡體   English   中英

不知道如何使用模板調用類函數

[英]Not sure how to call a class function using templates

我正在使用模板創建自己的字典(不,我不能,我不會使用STL中的任何內容)

我想要一個非常簡單的搜索功能,但我有一個小問題。

template <typename TElement>
void Dictionary<TElement>::search(TElement ADT, int key) {  // Abstract Data Type
    inf flag = 0;
    index =  int (key % max);
    temp[index] = root[index]; // root of the hash
    while (temp[index]->next != NULL) {
        if(temp[index]->data->key_actual_name == key) { @things happen }
    }
}

我想要理解:如何使用模板,以便我可以有temp[index]->data-><template call>如果這有任何意義

我想通過使用來調用字典:Class_type == TElement和“key”總是一個int但它可以是不同的東西。 它可能是ID或電話號碼。 問題是我需要使用密鑰的實際名稱( if(temp[index]->data->ID (or phone or what ever) == key ){@things happen}),我想我可以在這里使用模板但我不知道怎么做。

也許相關:

template <typename TElement>
typedef struct list{
    TElement data;
    struct list *next;
}node_type;
node_type *ptr[max], *root[max], *temp[max]; 

另外,如果我使用key_actual_name的模板,實現將如何工作以及如何調用該函數?

您可以從標准庫函數中獲得一些靈感,例如find_if ,它具有用於比較的額外參數。

template <class InputIterator, class Predicate>
InputIterator find_if ( InputIterator first, InputIterator last, Predicate pred );

然后,您可以傳遞一個參數,告訴search功能如何找到您要查找的密鑰。 或許可以替換使用==

if(pred(temp[index]->data, key)) { @things happen }

並傳遞不同的pred函數,用於將密鑰與適當的成員進行比較。

如果我理解正確:

temp[index]->data->key_actual_name

解析為TElement的數據成員,這是一個int,您希望它是一個模板。 如果是這種情況,你可以這樣做:

template <template <class> class TElement, typename TKey>
struct node_type
{
    TElement<TKey> data;
    node_type *next;
};

template <template <class> class TElement, typename TKey>
class Dictionary
{
    typedef node_type<TElement, TKey> node_t;
    node_t _root;

    void search(node_t& node, const TKey& key)
    {
        TKey& thekey = node.data.key_actual_name;
        // Do some algorithm
    }
public:
    void search(const TKey& key)
    {
        search(_root, key);
    }
};

template <class T>
struct Element
{
    T key_actual_name;
};

int main(int argc, char ** argv)
{
    Dictionary<Element, int> dic1;
    dic1.search(1);

    Dictionary<Element, char> dic2;
    dic2.search('a');

    return 0;
}

如您所見,Element有一個模板參數,因此您可以將key_actual_name的類型更改為適合您的情況,但讓搜索功能以通用方式訪問它(假設它具有operator == overload)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM