LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How to write a stream inserter for a template class (https://www.linuxquestions.org/questions/programming-9/how-to-write-a-stream-inserter-for-a-template-class-871582/)

hda7 03-28-2011 07:42 PM

How to write a stream inserter for a template class
 
I had some trouble doing this but finally figured it out. Here is a general solution:
Code:

#include <iostream>
using namespace std;

// Pre-declare class template...
template <class T> class MyTemplate;

// So we can pre-declare inserter...
template <class T> ostream &operator<<(ostream &stream, const MyTemplate<T> &t);

// So when we define the class template...
template <class T> class MyTemplate {
    // We can declare inserter a friend.
    friend ostream &operator<< <T> (ostream &stream, const MyTemplate<T> &t);
    ...
}

// Now inserter can access MyTemplate's private members
template <class T> ostream &operator<<(ostream &stream, const MyTemplate<T> &t) {
    ...
}

Hope this helps someone.

EricTRA 03-31-2011 01:56 AM

Hello,

Thanks for sharing your solution. Off the Zero Reply List.

Kind regards,

Eric


All times are GMT -5. The time now is 06:32 PM.