0

Disclaimer: this is a homework assignment, but nothing in the notes or our textbook seems to answer my question, so I'm coming here.

I have a Queue template class, and one of the things I need to do is overload the + operator to merge two Queue objects. I've written it, and I wanted to test it, so I wrote:

Queue<int, 25> sum = even + odd;

where even and odd are both Queue objects (even is Queue<int, 15> and odd is Queue<int, 10>)

This is my declaration of operator+:

Queue operator+(const Queue& obj) const;

And the function implementation header, which is implemented outside the class declaration (if that matters, I don't know):

template <typename T, int capacity>  
Queue<T, capacity> Queue<T, capacity>::operator+(const Queue& obj) const {
    Queue<T, 25> result; // not the literal 25, but effectively 25 just for demonstration  
    // some logic  
    return result;
}

These are the errors I'm getting:

error: no match for 'operator+' (operand types are 'Queue<int, 15>' and 'Queue<int, 10>')
no known conversion for argument 1 from 'Queue<int, 10>' to 'const Queue<int, 15>&'

I tried writing an add(const Queue& obj) method, but that spat out even more errors, because neither class could convert to Queue<int, 25>.

I've also tried changing which Queue's in the implementation have a template argument added to them, but that also just gave more errors.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770

1 Answers1

3

Your operator+ only allows the same Queue type to be passed to it, and returned from it. But Queue<int, 15>, Queue<int, 10>, and Queue<int, 25> are all different and distinct types. You need to use a separate set of template parameters on the operator's input parameter and return type, eg:

template <typename T, int capacity>  
class Queue
{
...
    template <int Other_capacity>
    Queue<T, capacity + Other_capacity> operator+(const Queue<T, Other_capacity>& obj) const;
...
};
template <typename T, int capacity>
template <int Other_capacity>
Queue<T, capacity + Other_capacity> Queue<T, capacity>::operator+(const Queue<T, Other_capacity>& obj) const {  
    Queue<T, capacity + Other_capacity> result;
    // some logic  
    return result;
}

Online Demo

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • I actually didn't know you could have multiple templates in a header, thanks for that! That implementation looks so sensible after reading it, and it let my program compile (when I commented out all the other logic for the operator lol). Thank you! – Sandman Feb 23 '22 at 18:34