LinuxQuestions.org
Register a domain and help support LQ
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices

Reply
 
Search this Thread
Old 03-28-2011, 07:42 PM   #1
hda7
Member
 
Registered: May 2009
Distribution: Debian wheezy
Posts: 244

Rep: Reputation: 31
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.
 
Old 03-31-2011, 01:56 AM   #2
EricTRA
Guru
 
Registered: May 2009
Location: Gibraltar, Gibraltar
Distribution: Fedora 18 with Awesome WM
Posts: 6,805
Blog Entries: 1

Rep: Reputation: 1290Reputation: 1290Reputation: 1290Reputation: 1290Reputation: 1290Reputation: 1290Reputation: 1290Reputation: 1290Reputation: 1290
Hello,

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

Kind regards,

Eric
 
  


Reply

Tags
c++, ostream, template


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
dynamic template class erat123 Programming 1 06-20-2007 01:10 PM
c++ class template doesn't work!! tagigogo Programming 2 11-02-2005 04:45 PM
Template class with a template member... Nicholas Bishop Programming 3 02-21-2005 08:27 PM
template class ckcheung0927 Programming 3 11-28-2004 03:59 PM
C++ template class syntax rong Programming 12 08-13-2003 12:26 PM


All times are GMT -5. The time now is 01:07 AM.

Main Menu
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration