将模板类作为参数传递

时间:2013-10-29 14:41:51

标签: c++ class templates parameters constructor

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

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中启动它的对象并更改输入类型等我有这个工作。

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的类,该类允许他们从哈希类中调用函数。

1 个答案:

答案 0 :(得分:15)

您可以使用:

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

Live demo