传递模板类作为参数

传递模板类作为参数

本文介绍了传递模板类作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将模板化类传递给另一个类的构造函数?我试图将模板化的哈希表类传递给菜单类,这将允许我然后让用户决定哈希表的类型.

How do I pass a templated class to the constructor of another class? I am trying to pass a templated hash table class to a menu class which will allow me to then allow the user to decide the type of the hash table.

template <class T>
class OpenHash
{
private:
    vector <T> hashTab;
    vector <int> emptyCheck;
    int hashF(string);
    int hashF(int);
    int hashF(double);
    int hashF(float);
    int hashF(char);

public:
    OpenHash(int);
    int getVectorCap();
    int addRecord (T);
    int sizeHash();
    int find(T);
    int printHash();
    int deleteEntry(T);
};

template <class T>
OpenHash<T>::OpenHash(int vecSize)
{
    hashTab.clear();
    hashTab.resize(vecSize);
    emptyCheck.resize(vecSize);
    for (int i=0; i < emptyCheck.capacity(); i++)
    {
        emptyCheck.at(i) = 0;
    }
}

所以我有一个以模板为类的Open哈希类,因为它应该允许添加任何类型,所以如果在我的main中初始化它的对象并更改输入类型等,我就可以使用.

So I have this class Open hash that is templated, because it supposed to allow for any type to be added, I have this working if initiate a object of it in my main and change input types etc.

int main ()
{
   cout << "Please input the size of your HashTable" << endl;
   int vecSize = 0;
   cin >> vecSize;
   cout << "Please select the type of you hash table integer, string, float, "
           "double or char." << endl;
   bool typeChosen = false;
   string typeChoice;
   cin >> typeChoice;
while (typeChosen == false)
{
    if (typeChoice == "int" || "integer" || "i")
    {
        OpenHash<int> newTable(vecSize);
        typeChosen = true;
    }
    else if (typeChoice == "string" || "s")
    {
        OpenHash<string> newTable(vecSize);
       hashMenu<OpenHash> menu(newTable);
        typeChosen = true;

    }
    else if (typeChoice == "float" || "f")
    {
        OpenHash<float> newTable(vecSize);
        typeChosen = true;
    }
    else if (typeChoice == "double" || "d")
    {
        OpenHash<double> newTable(vecSize);
        typeChosen = true;
    }
    else if (typeChoice == "char" || "c" || "character")
    {
        OpenHash<char> newTable(vecSize);
        typeChosen = true;
    }
    else
    {
        cout << "Incorrect type";
    }
}
return 0;
}

在我的主要文章中,我想问用户创建哈希表的类型是什么.根据他们输入的内容,应创建具有所需类型的此类的实例,然后将其传递给另一个名为menu的类,该类应允许他们从哈希类中调用函数.

In my main I want to ask the user what type they which to make the hash table. depending what they enter it should create a instance of this class with the type they want and then pass this to another class called menu which should allow them to call functions from the hash class.

推荐答案

您可以使用:

class Ctor {
public:
    Ctor(const Other<int>&);    // if you know the specific type
};

或:

class Ctor {
public:
    template<class T>
    Ctor(const Other<T>&);      // if you don't know the specific type
};

这篇关于传递模板类作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 05:47