繁体   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