问题描述
我无法弄清楚如何调用一个模板函数,该函数假设将一个字符串和College对象作为main.cpp中的参数。
这是我在LinkedListADT.h中的模板:
#ifndef LINKED_LIST_H
#define LINKED_LIST_H
#include "ListNodeADT.h"
template <class T>
class LinkedList
{
private:
ListNode<T> *head;
int length;
public:
LinkedList(); // constructor
~LinkedList(); // destructor
// Linked list operations
void insertNode(const T &);
bool deleteNode(const T &);
bool searchList(const T &,T &) const;
};
这是我到目前为止在LinkedListADT.h文件中为搜索功能编写的内容:
template <class T,class S>
bool LinkedList<T,S>::searchList(const S &target,T &dataOut) const
{
bool found = false; // assume target not found
ListNode<T> *pCur;
while (pCur && pCur->getData().getCode() != target){
/*Code to search*/
return found;
}
这是我main.cpp中的搜索功能,该功能从头文件中调用searchList,该头文件接受用户输入的大学代码。假设使用字符串输入调用searchList并尝试在链接列表中找到与大学代码匹配的内容:
void searchManager(const LinkedList<College> &list)
{
string targetCode = "";
College aCollege;
cout << "\n Search\n";
cout << "=======\n";
while(toupper(targetCode[0]) != 'Q')
{
cout << "\nEnter a college code (or Q to stop searching) : \n";
cin >> targetCode;
if(toupper(targetCode[0]) != 'Q')
{
if(list.searchList(targetCode,aCollege))
/*Code to display college*/
else
cout << "Not Found";
}
}
cout << "___________________END SEARCH SECTION _____\n";
}
我确定这不是将模板函数写入头文件的方法,因为这也会更改其他模板函数(插入,删除等)的模板。我会很感激关于正确编写方法的任何建议。谢谢大家!
解决方法
我如何定义一个可以是一两个的模板类 参数? (来自评论)
您可以使用可变模板完成此操作,但这不是您所需要的。相反,您需要单参数模板类的模板成员函数,如下所示:
template <class T>
class LinkedList
{
//...
public:
//...
template<class S>
bool searchList(const S& target,T& result) const;
};
将函数定义放在类中比较容易,但是如果您坚持在外部定义它,则语法如下:
template<class T>
template<class S>
bool LinkedList<T>::searchList(const S& target,T& result) const
{
//...
}
一旦有了它,就应该编译从main()
调用它的方式。