问题描述
我已经创建了模板类T的模板类LinkedList,并且在该类中,我想实现一个函数入队,该入队采用通用类型D的数据,并以数据D作为参数调用T构造函数.
I have made a template class LinkedList of template class T and within this class, I want to implement a function enqueue that takes data of a general type D and calls the T constructor on with the data D as the parameter.
这是我班级的定义:
template<class T>
struct Node {
struct Node *_nextNode;
struct Node *_prevNode;
T *_value;
int _location;
};
template<class T>
class LinkedList {
private:
Node<T> *_firstNode;
Node<T> *_lastNode;
int _size;
public:
LinkedList<T>();
LinkedList<T>(const int size);
~LinkedList<T>();
template<typename D>
bool enqueue(D &newData);
bool dequeue();
T* find(const int location);
};
这是我声明函数入队的地方:
template<class T, typename D>
bool LinkedList<T>::enqueue(D &newData) {
Node<T> *newNode = new Node<T>;
newNode->_value = new T(newData);
newNode->_location = _lastNode->_location + 1;
_lastNode->_nextNode = newNode;
newNode->_prevNode = _lastNode;
_lastNode = newNode;
_lastNode->_nextNode = NULL;
_size++;
return true;
}
尝试编译时,我得到:
LinkedList.cpp:76:6: error: prototype for ‘bool LinkedList<T>::enqueue(D&)’ does not match any in class ‘LinkedList<T>’
bool LinkedList<T>::enqueue(D &newData) {
^~~~~~~~~~~~~
LinkedList.cpp:29:7: error: candidate is: template<class T> template<class D> bool LinkedList<T>::enqueue(D&)
bool enqueue(D &newData);
忽略入队函数的实际内容,与以前的实现相比,我还没有更改.任何帮助,将不胜感激.谢谢.
Ignore the actual content of the enqueue function, I have not changed that yet from my previous implementation. Any help would be appreciated. Thanks.
推荐答案
您需要将函数体定义为:
You need to define your function body as:
template <typename T>
template <typename D>
bool LinkedList<T>::enqueue (D& newData) {
// ...
}
此外, const D&
可能更干净.最好使用完美的转发,以允许传递任何类型的引用类型:
Also, const D&
is probably cleaner. It would be even better to use perfect forwarding, to allow passing any kind of reference type:
template <typename T>
template <typename D>
bool LinkedList<T>::enqueue (D&& newData) {
// ...
newNode->_value = new T (std::forward<D>(newData));
}
这也可以与构造函数的任意数量的参数一起使用:
This can also be made to work with an arbitrary number of parameters to the constructor:
template <typename T>
template <typename... D>
bool LinkedList<T>::enqueue (D&&... newData) {
// ...
newNode->_value = new T (std::forward<D>(newData)...);
}
此外,您的代码也不是异常安全的.如果 T
构造函数引发异常,则将永远不会释放 newNode
实例,从而导致内存泄漏.
Additionally, your code isn't exception-safe. If the T
constructor throws an exception, the newNode
instance is never freed, causing a memory leak.
此外,请勿使用 NULL
,但请尽可能使用 nullptr
(即,如果您可以使用C ++ 11).
Also, don't use NULL
, but use nullptr
if possible (i.e. if you can use C++11).
这篇关于模板类定义中的模板方法与声明不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!