Template Method within Template class definition does not match declaration

前端 未结 1 422
独厮守ぢ
独厮守ぢ 2021-01-21 19:58

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

相关标签:
1条回答
  • 2021-01-21 20:50

    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).

    0 讨论(0)
提交回复
热议问题