PDA

View Full Version : operator<< and templates



mickey
29th May 2008, 21:35
Hello,
how can I overload << with templates, please?



template <class T = int, size_t N = 100>
class Stack {
T _data[N];
size_t _index;

public:
Stack() : _index(0) { }
void push(const T& value) {
if ( _index != N) _data[_index] = value;
else printf("stack full\n");
}


friend std::ostream& operator<<(std::ostream& os, const Stack<T>& stack) {
for (int i=0; i < N; ++i)
os << _data[i] << " ";
return os;
}
};



error C2597: illegal reference to non-static member 'Stack<>::_data'
.....and others.....

DeepDiver
30th May 2008, 14:09
Hi,
try this:
1.) move the operator<< outside the class
2.) add the template declaration to the operator (template <class T = int, size_t N = 100>)
3.) fix the compiler error: _data is a member of stack

Take care,

Tom

mcosta
30th May 2008, 14:31
Your code has two error:

1) You cannot define friend function body in the class declaration

2) You must declare friend function as template

3) In push function you must increment _index

The following code compile and run right



#include <iosfwd>

template <class T = int, size_t N = 100>
class Stack {
T _data[N];
size_t _index;

public:
Stack() : _index(0) { }
void push(const T& value) {
if ( _index != N)
{
_data[_index] = value;
++_index;
}
else
printf("stack full\n");
}

template <typename TYPE, size_t SIZE>
friend std::ostream& operator<<(std::ostream& os, const Stack<TYPE, SIZE>& stack);
};

template <typename T, size_t N>
std::ostream& operator<<(std::ostream& os, const Stack<T, N>& stack)
{
for (size_t i=0; i < stack._index; ++i)
os << stack._data[i] << " ";
return os;
}




int main()
{
Stack<int, 10> st;
st.push(2);
st.push(5);
st.push(3);

std::cout << st << std::endl;

return 0;
}

mickey
30th May 2008, 17:13
sorry,
this code seems work properly; I missed "stack." in os << _data. why does it work?


template <class T = int, size_t N = 3>
class Stack {
//enum { N = 100 };
T _data[N];
size_t _index;

public:
Stack() : _index(0) { }
void push(const T& value) {
if ( _index != N) _data[_index++] = value;
else printf("stack full\n");
}

friend std::ostream& operator<< (std::ostream& os, const Stack<T>& stack) {
for (int i=0; i < N; ++i)
os << stack._data[i] << " ";

return os << endl;
}

};