简体   繁体   中英

Template specialization when having a constant parameter

I have class Queue that is implemented with templates, one parameter for the type and one constant parameter for the size of the queue.

  template <typename T, int N>
  class Queue
  {
     .....
     void enqueue(T x);
  }

I want to specialize the enqueue method, for the typename but I can not figure how to do this.

 template <typename T, int N>
 void Queue<Heap<struct infoNod>, N>::enqueue(Heap<struct infoNode> x)
 {}

For specializing the entire class I am not sure if i do it right: in header:

 template <>
 class Queue<Heap<struct infoNode>, 100>
 {
    public:
       void enqueue(Heap<struct infNode> x);
 }; 

in cpp:

template <>
 void Queue<Heap<struct infoNod>, 100>::enqueue(Heap<struct infoNode> x) {}

errors:

Queue.cpp:77:6: error: template-id ‘enqueue<>’ for ‘void Queue<Heap<infoNod>, 100>::enqueue(Heap<infoNode>)’ does not match any template declaration
 void Queue<Heap<struct infoNod>, 100>::enqueue(Heap<struct infoNode> x)
      ^
Queue.cpp:77:78: note: saw 1 ‘template<>’, need 2 for specializing a member function template
 void Queue<Heap<struct infoNod>, 100>::enqueue(Heap<struct infoNode> x)

Since you have a class template with a non-template enqueue() method, you can only partially specialize the whole class, not the individual method:

template <typename T, int N>
class Queue
{
    void enqueue(T x) { /* default implementation */ }
};

template<int N>
class Queue<Heap<InfoNode>, N>
{
   void enqueue(Heap<InfoNode> x) { /* specialized implementation */ }
};

Another alternative is not to specialize the whole Queue class but to make enqueue() delegate to a small helper class that will be specialized.

I have solved by extending the Queue class:

class QueueSpec: public Queue<Heap<struct infoNode>, SIZE >
{
    public:
        void enqueue(Heap<struct infoNode> x);
};

---
void QueueSpec::enqueue(Heap<struct infoNode> x) {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM