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 con
You need to define your function body as:
template <typename T>
template <typename D>
bool LinkedList<T>::enqueue (D& newData) {
// ...
}
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)...);
}
Additionally, your code isn't exception-safe. If the T
constructor throws an exception, the newNode
instance is never freed, causing a memory leak.
Also, don't use NULL
, but use nullptr
if possible (i.e. if you can use C++11).