Template Method within Template class definition does not match declaration

前端 未结 1 453
独厮守ぢ
独厮守ぢ 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 
    template 
    bool LinkedList::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 
    template 
    bool LinkedList::enqueue (D&& newData) {
      // ...
      newNode->_value = new T (std::forward(newData));
    }
    

    This can also be made to work with an arbitrary number of parameters to the constructor:

    template 
    template 
    bool LinkedList::enqueue (D&&... newData) {
      // ...
      newNode->_value = new T (std::forward(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)
提交回复
热议问题