Can someone tell me whats wrong with my code. I’m guessing that I didn’t overload << correctly, but I’m not sure how to fix it.
The below code implements a simple Stack container. It fails at cout << si;
update: Made suggested changes, still not compiling.
update2: Got it! Thanks!
#include <iostream>
using namespace std;
template <typename T = int, int N = 10>
struct Stack
{
T elems[N];
unsigned int size;
Stack()
{
size=0;
}
void push(T e)
{
elems[size]=e;
size++;
}
T pop()
{
size--;
return elems[size];
}
template <typename T, int N>
friend ostream& operator << (ostream& os, const Stack<T, N> &stack);
};
template <typename T, int N>
ostream& operator << (ostream& os, const Stack<T, N> &stack)
{
for (unsigned int i=0; i<N; i++)
{
os << stack.elems[i];
}
return os;
}
int main()
{
Stack<> si;
si.push(3);
cout << si;
}
The problem with this template is that the parameter
Ncannot be inferred from either of the function arguments because you are using the default template argument for theStackargument.Looking at your implementation, you almost certainly didn’t intend this as you use
Nas the loop bound whereasStack<T>has 10 elements. You probably meant to write:Also, your friend declaration needs to match the template, at the moment the friend declaration is declaring a non-template friend overload.
This would declare an appropriate friend template.