template on self defined classes

Hi,

It's been quite a while since I've actually programmed in C++, during school days.
I'm relearning C++ now, so far so good, but I'm struggling with something which I can't quite figure out.

I've got the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template <typename T>
class Section
	{
	private:

		std::vector<T> container;
                ...
        public:	
                void print();
};
...
template <typename T> void Section<T>::print()
{
	typename std::vector<T>::iterator It1;
	It1 = container.begin();
	for ( It1 = container.begin( ) ; It1 != container.end( ) ; ++It1 )
		std::cout << " " << *It1<<std::endl;
}


This code works for all standard types: integers, strings and whatnot...
But what if T is self defined.

To add and delete elements of a self defined T is no problem.
But I want to print some data residing in the self defined T.
Imagine if all Ts stored in the vector has an operator T.print().
How can I simply exectute T.print() for all elements in the vector using preferably an iterator.
I imagine i need an iterator for each seperate self defined data type?
How must I achieve this?

any help is welcome...
But what if T is self defined.


That code would work for any type T where the << operator is overloaded.

For example if you wanted it to work with class MyClass, you'd need to have the following operator defined:

1
2
3
4
5
6
ostream& operator << (ostream& stream, const MyClass& obj)
{
    // output 'obj' to 'stream' here

    return stream;
}


As long as you have that operator defined, the above print() function will work just fine.
Brilliant!

thanks Disch!
Topic archived. No new replies allowed.